异步函数返回promise,而不是值 [英] Async function returning promise, instead of value

查看:433
本文介绍了异步函数返回promise,而不是值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解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的阻塞.然后,我的函数返回原始值,但是时间变量设置为待处理的Promise而不是原始值.我想念什么?

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模块的顶层执行此操作,则某些环境现在支持即将到来的

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执行程序函数)由new Promise同步调用.
    • 这就是操作开始的原因,web3.eth.getBlock被同步调用以开始工作.
    • The function you pass to new Promise (the promise executor function) gets called synchronously by new Promise.
      • Which is why the operation starts, web3.eth.getBlock is called synchronously to start the work.

      这篇关于异步函数返回promise,而不是值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆