异步函数返回承诺,而不是值

发布于 2025-01-09 04:27:42 字数 498 浏览 1 评论 0原文

我试图了解 async/await 如何与 Promise 结合使用。

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。然后,我的函数返回原始值,但是时间变量设置为待处理的承诺而不是该原始值。我缺少什么?

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> }

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

掐死时间 2025-01-16 04:27:43

async 函数总是返回一个 Promise。这就是它报告异步工作完成情况的方式。如果您在另一个async函数中使用它,则可以使用await来等待其promise解决,但在非async中函数(通常在顶层或事件处理程序中),您必须直接使用 Promise,例如:

latestTime()
.then(time => {
    console.log(time);
})
.catch(error => {
    // Handle/report error
});

...尽管如果您在 JavaScript 模块的顶层执行此操作,则所有现代环境现在都支持 模块中的顶级 await:(

const time = await latestTime();

请注意,如果Promise 被拒绝,您的模块将无法加载。如果即使 Promise 失败,您的模块也能有意义地工作,请务必将其包装在 try/catch 中以处理 Promise 拒绝。 .)


可能(或者可能不)用显式的承诺回调术语来阐明 JavaScript 引擎如何在幕后处理您的 async 函数:

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);
    });
}

一些重要的注意事项:

  • 您传递给 new 的函数Promisepromise 执行器函数)由new Promise同步调用。
    • 这就是操作开始的原因,同步调用web3.eth.getBlock来开始工作。
  • Promise 执行器中抛出的任何错误(等)都会被 new Promise 捕获并转换为 Promise 拒绝。
  • Promise 回调中抛出的任何错误(例如我们传递的 then 错误)都将被捕获并转换为拒绝。

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
});

...though if you're doing this at the top level of a JavaScript module, all modern environments now support top-level await in modules:

const time = await latestTime();

(Note that if that promise is rejected, your module will fail to load. If your module can work meaningfully even if the promise fails, be sure to wrap that in try/catch to handle promise rejection.)


It might (or might not) throw some light on things to see, in explicit promise callback terms, how the JavaScript engine handles your async function under the covers:

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:

  • 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.
  • Any error (etc.) thrown within the promise executor gets caught by new Promise and converted into a promise rejection.
  • Any error (etc.) thrown within a promise callback (like the one we're passing then) will get caught and converted into a rejection.
情域 2025-01-16 04:27:43

异步前缀是 Promise 的一种包装器。

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;
}

是一样的

function latestTime() {
    return new Promise(function(resolve,success){
        const bl = web3.eth.getBlock('latest');
        bl.then(function(result){
            console.log(result.timestamp); // Returns a primitive
            console.log(typeof result.timestamp.then == 'function'); //Returns false - not a promise
            resolve(result.timestamp)
        })
}

Async prefix is a kind of wrapper for 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;
}

Is the same as

function latestTime() {
    return new Promise(function(resolve,success){
        const bl = web3.eth.getBlock('latest');
        bl.then(function(result){
            console.log(result.timestamp); // Returns a primitive
            console.log(typeof result.timestamp.then == 'function'); //Returns false - not a promise
            resolve(result.timestamp)
        })
}
拒绝两难 2025-01-16 04:27:43

无论如何,async 函数都会返回 Promise。返回值将是“Promise”,因此在您的情况下它将是:

async function latestTime(): Promise<some primitive> {
  const bl = await web3.eth.getBlock('latest');
  return bl.timestamp;
}

因此,您可以进一步使用它的功能,例如:

const time = await latestTime();

但是为了实现有关async/await功能的一般视图,最好阅读文档。

async function will return Promise anyway. Return value will be `Promise, so in your case it will be:

async function latestTime(): Promise<some primitive> {
  const bl = await web3.eth.getBlock('latest');
  return bl.timestamp;
}

So, further you can use it function like:

const time = await latestTime();

But for achieving general view about async/await feature it will be better to read documentation.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文