typescript 返回 Promise<void> 的异步函数在块的末尾是否有隐式返回?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44216949/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:35:07  来源:igfitidea点击:

Does a async function which returns Promise<void> have an implicit return at the end of a block?

javascripttypescriptes6-promise

提问by Gala

public async demo(): Promise<void> {
    // Do some stuff here
    // Doing more stuff
    // ... 
    // End of block without return;
}

Is a new Promise<void>returned implicitely at the end of the block in TypeScript/ES6?

Promise<void>在 TypeScript/ES6 的块末尾是否隐式返回了一个 new ?

Example for boolean type:

布尔类型示例:

class Test {

    public async test(): Promise<boolean> {
        return true;
    }

    public main(): void {

        this.test().then((data: boolean) => {

            console.log(data);

        });

    }

}

new Test().main();

This prints trueto the console because a returninside of a async function creates a new Promiseand calls resolve()on it with the returned data. What happens with a Promise<void>?

这会打印true到控制台,因为return异步函数的内部创建了一个新函数Promiseresolve()使用返回的数据调用它。会发生什么Promise<void>

回答by basarat

What happens with a Promise

Promise 会发生什么

Same thing with a function that returns void. A voidfunction returns undefined. A Promise<void>resolves to an undefined.

与返回void. 一个void函数返回undefined。APromise<void>解析为undefined

function foo(){}; console.log(foo()); // undefined
async function bar(){}; bar().then(res => console.log(res)); // undefined