Search code examples
javascriptasync-awaites6-promise

Is using await necessary with .then


I have an async function

async function f1 (){
  some db operation
  return result
}

What is the difference between the two code

await f1()
.then((result)=> something1. Can I use result here?)

vs

f1()
.then((result)=>something2. Can I use result here?)

Solution

  • TL:DR

    The difference is that the statement following the first code is executed asynchronously, whereas the statement following the second code is executed synchronously.


    Precedence of chaining (calling then) and await

    The await operator has lower precedence than both the . operator used for "member access" to access methods of a promise object, and function calls to the method once accessed. In fact, member access and function calls have the same priority and will be executed from left to right.

    Hence in this code

    await f1().then(result=>// code using the result)
    // next statement
    

    the await operator is waiting for the last promise in the chain to be fulfilled. You can use result in the fulfillment handler as a matter of course- that's how fulfilling the promise returned by f1() passes its return value to the next handler in the chain. The next statement is executed asynchronously, after the value of result has been determined and processed. More generally if the promise chain contained more than two promises, the next statement would be executed after the last promise in the chain becomes fulfilled.

    In the second code,

    f1().then(result=>// code using the result)
    // next statement
    

    you can still use result in the fulfillment handler - nothing has changed with how promise chains operate. But without the await operator, the statement following the promise chain is executed synchronously, without waiting for any promise in the chain to be settled, including the promise returned by f1().