简体   繁体   中英

Do we use await on async functions which use await?

I have a Rest API endpoint /foo/bar and I am calling it from and async function bar() and I am calling that function from another function foo () like so

async function bar () {
    let result;

    result = await $.ajax({}); /* pseudocode only */
    return result;
}

function foo () {
    let result;

    result = bar ();
    console.log ('This should display before the result, not after it');
    console.log (result);
    console.log ('This should display after the result, not before it');

foo();
 

I am getting inconsistent results and I want to know if it is because I need to instead make foo asynchronous like so

async function bar () {
    let result;

    result = await $.ajax({}); /* pseudocode only */
    return result;
}

async function foo () {
    let result;

    result = await bar ();
    console.log ('This should display before the result, not after it');
    console.log (result);
    console.log ('This should display after the result, not after it');

foo();

Basically my question is whether an await inside an async function renders that function synchronous (ie. it blocks the calling function until the await returns)?

You are correct. Async functions will return a Promise so, if you'd like to wait for the response of an async function, you will need the await.

an async function by definition returns a Promise so you deal with the result in the same way as any other Promise.

Which basically means you either do what's in your second snippet, with async/await :

async function foo () {
    let result;

    result = await bar ();
    console.log (result);
}

or alternatively you can use .then :

function foo() {
    bar().then(result => console.log(result));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM