我在使用 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/