简体   繁体   English

在等待完成之前返回的异步函数

[英]Async function returning before await is complete

I have two questions from the following example: 我从以下示例中得到两个问题:

Why is does x log before y? 为什么x在y之前记录? Why is xa Promise? 为什么xa承诺?

I'm expecting bar to wait for foo to resolve with the value 'Hello' before it logs and then returns it. 我期待bar在它记录之前等待foo以值'Hello'解析然后返回它。

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

What I'm expecting to see is 我期待看到的是

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

What I'm getting is 我得到的是

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

Shouldn't bar wait for foo to resolve before returning y ? 应该不是barfoo返回前解决y

Any help would be much appreciated! 任何帮助将非常感激!

Here is the documentation about async function : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function 以下是有关async function的文档: https//developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

And Promise object: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise Promise对象: https//developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

It is stated that an async function returns a Promise object which is in a pending state until it is resolved. 声明async function返回一个Promise对象,该对象在解析pending处于pending状态。


Now let's look at your 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. 您为x分配了返回值bar() ,这是一个Promise ,因为没有await关键字来停止执行(而且你不能添加一个,因为你在async function )这个promise被记录为pending因为async function bar()尚未返回。

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. 同时,在async function bar() ,为y分配async function foo()的返回值,它也是一个Promise ,但这次你等待结果。 After 2 seconds of waiting time, the promise is fulfiled and y is logged with the parameter of the resolve() method, which is Hello . 经过2秒的等待时间后,承诺得以实现,并使用resolve()方法的参数记录y ,即Hello

Thus the behaviour you witness is the expected one. 因此,您见证的行为是预期的行为。

You need to await the function: 你需要await这个功能:

let example = async () => {
    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 = await bar();

    console.log(x);
}

example();

You should use an await before calling bar() but, actually, you can use await just when you wrapped it by a async function like below: 你应该在调用bar()之前使用await ,但实际上,你可以使用await就像你用async函数包装它一样,如下所示:

async function Func() {

  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 = await bar();

  console.log(x);

}

When you execute the Func(); 当你执行Func(); your expectation will fire. 你的期望会激发。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 异步 function 在等待完成之前触发 setstate - async function triggers setstate before await is complete 异步 function 在返回之前不等待等待 - Async function doesn't wait with await before returning 在调用函数完成之前,异步/等待返回未定义 - Async/Await is returning undefined before the called function completes 在第二次等待-Async / await之前等待第一次等待完成 - Wait for the first await to complete before second await -Async/await Async/await 问题,Async/await function 在值被放入新的 state 之前返回 true - Async / await problem, The Async / await function is returning true before the value is placed in the new state 异步等待 map 不等待异步 function 在 map ZC1C425268E68385D14ZA7 映射之前完成 - Async Await map not awaiting async function to complete inside map function before mapping next item Async/Await 在执行前仍然返回数据 - Async/Await still returning data before execution axios async await Cloud Function 在 axios 完成 post 请求之前返回 - Axios async await Cloud Function returning before axios completes post request 让 React JS 在运行之前等待异步函数完成 - Make React JS await for a async func to complete before running Async/Await : 被调用的函数没有等待和返回值 - Async/Await : called function is not awiting and returning value
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM