Search code examples
javascriptecmascript-6promise

What happens when you mix then/catch with await in Javascript


What happens if you mix then/catch and await for Promises in Javascript?

await thisReturnsAPromise()
  .then(() => /* do something */)
  .catch(() => /* do something */);
  • Does it await the Promise twice? Once for the await and once for the then callback?
  • Does then return a new Promise or is it exactly the same as the function returns?
  • The await will resolve after then, but are they resolved at the same time or is there a tiny delay between?


What is returned in this case and why?:

const awaitResult = await thisReturnsAPromise() // returns a Promise<number>
  .then((thenResult) => /* do something */)
  .catch(() => /* do something */);

It is clear that it is not ideal to mix the approaches so the question is what happens when you do.


Solution

  • Here await works as if we were promise chaining (kind of)

    Example:

    async function test() {
        let result = await Promise.resolve(5).then((data) => {
            console.log('then: ', data);
            return 10;
        })
        console.log('await:', result);
    }
    
    test();
    
    [LOG]: "then: ",  5 
    [LOG]: "await:",  10
    

    Basically, await returns the fulfillment value of the promise or thenable object, or, if the expression is not thenable, the expression's own value. (docs). In the example, we can see that await returned 10 due to then returning a promise that fulfills to 10