为什么我不能从async提供的函数中获得我期望的结果?

时间:2018-02-12 01:43:31

标签: javascript node.js async-await

我有一些代码如下

'use strict';
function greeting() {
  console.log('Hello ' + getName());
}

async function getName() {
  return 'Fred';
}

greeting();

我原以为输出为Hello Fred,但它会返回Hello[object Promise]。我知道没有必要用getName()来装饰async,我只是描述了我遇到的类似情况。

1 个答案:

答案 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