Home > OS >  await vs then - accessing returned values
await vs then - accessing returned values

Time:10-14

Trying to get my head around the subtle (sic) differences between await vs then. I've read most of the posts here, so I get that async functions return a promise.

Using await (with an async function) returns a var that can be used downstream, but using .then (with an async function) does not (at least for me) likewise return a var that can be accessed outside the then clause), since it is processed asynchronously and downstream references are processed synchronously - outside the .then clause, the var (in my example) is undefined.

I understand why my example is behaving the way it does, but my question is - is there a way to use .then with an async function, such that the result can be accessed downstream of the function execution?

let x, y, z;

async function foo ( num ) {
    return Promise.resolve ( num   10 );
}

async function bar (num) {
    return num   20;
}

async function baz (num) {
    return Promise.resolve ( num   30 );
}

async function main (){
    x = await foo(10);
    console.log('foo returned (after await): '  x); // no hay problema!

    y = await bar (10);
    console.log('bar returned (after await): '  y); // no hay problema!

    baz (10)
        .then ( (result) =>{
            z = result;
        });
    console.log('baz returned: '  z); // undefined...executes before .then completes...
}

main(); 

CodePudding user response:

is there a way to use .then with an async function, such that the result can be accessed downstream of the function execution?

No. There's no reliable way to do that.

Moreover, you shouldn't need to do that in the first place. Whatever you want to do with the data after the promise chain can be done inside the callback function, once the data is available.

Using await (with an async function) returns a var that can be used downstream

Right but that's only possible because of how async-await is transformed in the promise chain. That "downstream" code is actually wrapped in a callback function of then() method.

CodePudding user response:

there is no way to make a promise behave synchronously like you desire. The only way is to move your code dependent of the promise inside the then block and continue there.

baz (10)
        .then ( (result) =>{
            z = result;
            console.log('baz returned: '  z); // undefined...executes before .then completes...
        });

CodePudding user response:

You have to either wait for every promise to resolve with await so code will behave in non async manner, or chain callback with then

await baz (10)
        .then ( (result) =>{
            z = result;
        });

    console.log('baz returned: '  z)

so everything is done, or

baz (10)
        .then ( (result) =>{z = result;})
        .then ( () =>{console.log('baz returned: '  z)})
  • Related