我有一些代码如下
'use strict';
function greeting() {
console.log('Hello ' + getName());
}
async function getName() {
return 'Fred';
}
greeting();
我原以为输出为Hello Fred
,但它会返回Hello[object Promise]
。我知道没有必要用getName()
来装饰async
,我只是描述了我遇到的类似情况。
答案 0 :(得分:4)
必须使用await
关键字调用异步函数。 async
函数始终返回带有返回值的promise,await
" pulls"承诺的价值。 await
只能在异步函数中使用。
async function getName() {
return 'Fred'
}
async function greeting() {
console.log('Hello ' + await getName())
}
greeting()
// while this isn't *required*, it's good practice to always handle promise errors
.catch(error => console.error(error))
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function