异步函数在等待完成之前返回 [英] Async function returning before await is complete

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

问题描述

以下示例中有两个问题:

I have two questions from the following example:

为什么x在y之前记录?为什么x是一个承诺?

Why is does x log before y? Why is x a Promise?

我希望 bar 等待 foo 用值'Hello'解析后再返回./p>

I'm expecting bar to wait for foo to resolve with the value 'Hello' before it logs and then returns it.

let foo = () => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve('Hello');
        }, 2000);
    })
}

let bar = async () => {
    let y = await foo();
    console.log(y);
    return y;
}

let x = bar();

console.log(x);

我希望看到的是

'Hello' // console.log(y)
'Hello' // console.log(x)

我得到的是

 Promise {<pending>}  // console.log(x)
 'Hello'              // console.log(y)

bar 是否应该等待 foo 解析后返回 y ?

Shouldn't bar wait for foo to resolve before returning y?

任何帮助将不胜感激!

推荐答案

以下是有关异步功能的文档: Promise 对象:据说,一个 async函数返回一个 Promise 对象,该对象处于 pending 状态直到被解决.

It is stated that an async function returns a Promise object which is in a pending state until it is resolved.

现在让我们看看您的代码:

Now let's look at your code:

您将 bar()的返回值分配给 x ,这是一个 Promise ,因为没有 await 关键字以停止执行(并且您不能添加一个,因为您不在 async函数之内),因为 async函数bar(),此承诺记录为未决code>尚未返回.

You assign to x the return value of bar(), which is a Promise, since there is no await keyword to stop the execution (And you can not add one, because you are outside of an async function) this promise is logged as pending because the async function bar() has not yet returned.

同时,在 async函数bar()中,将 async函数foo()的返回值分配给 y Promise ,但是这次您要等待结果.经过2秒钟的等待时间后,将履行诺言,并使用 resolve()方法的参数( Hello )记录 y .

Meanwhile, in the async function bar() you assign to y the return value of the async function foo() which is also a Promise, but this time you make it await for the result. After 2 seconds of waiting time, the promise is fulfiled and y is logged with the parameter of the resolve() method, which is Hello.

因此,您看到的行为是预期的行为.

Thus the behaviour you witness is the expected one.

这篇关于异步函数在等待完成之前返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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