异步函数返回承诺,而不是价值 [英] Async function returning promise, instead of value
问题描述
我正在尝试了解 async/await 如何与 promise 结合使用.
I'm trying to understand how async/await works in conjunction together with promises.
async function latestTime() {
const bl = await web3.eth.getBlock('latest');
console.log(bl.timestamp); // Returns a primitive
console.log(typeof bl.timestamp.then == 'function'); //Returns false - not a promise
return bl.timestamp;
}
const time = latestTime(); // Promise { <pending> }
问题
据我所知,await 应该是阻塞的,在上面的代码中,它似乎阻塞了返回带有原始 timestamp
的对象 bl
.然后,我的函数返回原始值,但是时间变量设置为挂起的承诺而不是该原始值.我错过了什么?
Issue
As far as I understand, await should be blocking and in the code above it seemingly blocks returning an object bl
with the primitive timestamp
. Then, my function returns the primitive value, however the time variable is set to a pending promise instead of that primitive. What am I missing?
推荐答案
async
函数总是返回一个 promise.这就是它报告异步工作完成的方式.如果你在另一个 async
函数中使用它,你可以使用 await
来等待它的承诺解决,但在非async
函数(通常在顶层或在事件处理程序中),您必须直接使用承诺,例如:
An async
function always returns a promise. That's how it reports the completion of its asynchronous work. If you're using it in another async
function, you can use await
to wait for its promise to settle, but in a non-async
function (often at the top level or in an event handler), you have to use the promise directly, e.g.:
latestTime()
.then(time => {
console.log(time);
})
.catch(error => {
// Handle/report error
});
如果您在 JavaScript 模块的顶层执行此操作,某些环境现在支持即将推出的 模块中的顶级await
:
If you're doing this at the top level of a JavaScript module, some environments now support the upcoming top-level await
in modules:
const time = await latestTime();
JavaScript 引擎正在获得对顶级 await
的支持,并且 Webpack 已经例如,对它的实验支持.
JavaScript engines are getting support for top-level await
, and Webpack has experimental support for it, for instance.
以下是您的 async
函数在明确的 Promise 术语中的粗略翻译:
Here's a rough translation of your async
function in explicit Promise terms:
function latestTime() {
return new Promise((resolve, reject) => {
web3.eth.getBlock('latest')
.then(bl => {
console.log(bl.timestamp);
console.log(typeof bl.timestamp.then == 'function');
resolve(bl.timestamp);
})
.catch(reject);
});
}
关于此的一些重要说明:
Some important notes on that:
- 您传递给
new Promise
(promise executor 函数)的函数被new Promise
同步调用.- 这就是操作开始的原因,
web3.eth.getBlock
被同步调用以开始工作.
- The function you pass to
new Promise
(the promise executor function) gets called synchronously bynew Promise
.- Which is why the operation starts,
web3.eth.getBlock
is called synchronously to start the work.
这篇关于异步函数返回承诺,而不是价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- Which is why the operation starts,
- 这就是操作开始的原因,