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
Does a async function which returns Promise<void> have an implicit return at the end of a block?
提问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 true
to the console because a return
inside of a async function creates a new Promise
and calls resolve()
on it with the returned data. What happens with a Promise<void>
?
这会打印true
到控制台,因为return
异步函数的内部创建了一个新函数Promise
并resolve()
使用返回的数据调用它。会发生什么Promise<void>
?
回答by basarat
What happens with a Promise
Promise 会发生什么
Same thing with a function that returns void
. A void
function 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