node.js - 在异步/等待中包装 promise

标签 node.js promise async-await ecmascript-next

我在使用 async/await 和从 Promise 返回值时遇到了一些困难。

function test () {
  return new Promise((resolve, reject) => {
    resolve('Hello')
  })
} 

async function c() {
  await test()
}

据我了解,我应该能够通过以下方式获得值(value):

console.log(c())

但显然我在这里遗漏了一点,因为这返回了一个 promise 。它不应该打印“你好”吗?类似地,我不清楚在将回调包装在异步/等待之前是否需要将其转换为 promise ?

最佳答案

I am missing a point here as this returns a promise. Shouldn't console.log(c()) print "hello"?

不,async 函数总是返回 promise 。它们并没有神奇地同步运行异步代码 - 相反,它们将看似同步的代码(虽然散布着 await 关键字)变成了异步运行的代码。

您可以在异步函数中获取结果值:

async function c() {
  const result = await test()
  console.log(result);
  return 'World';
}
c().then(console.log);

I am unclear as to whether a callback needs to be converted to a promise before wrapping it in async/await?

是的,您只能await promise 。参见 How do I convert an existing callback API to promises?了解如何进行转换。

关于node.js - 在异步/等待中包装 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38839130/

相关文章:

c# - Task.Wait 总是返回 false 尽管任务已完成

javascript - 文件结构 : Requiring Sub-Modules in Node. js

javascript - 我可以在 Node.js 和 Express 中运行单个 .js 文件吗?

javascript - 在 Node js失败后重试自己

javascript - react -将Promise与Edge一起使用时无法解析错误

c# - 导航期间出现 RaiseCanExecuteChanged COM 异常?

node.js - 异步等待与 nodejs 7

node.js - 在对话 Node alexa-sdk 期间更改卡

Node.js grep 进程(但不包括 self)

jquery - 是否有任何 jQuery 版本符合 Promise/A 规范?