Making asynchronous code look synchronous

Try to convert the following Promise code to async/await:

const doSomething = () => {  return p1().then(res1 => {      return p2().then(res2 => {          // finally we need both res1 and res2           return p3(res1, res2)        })    })}

You see? Even with promises, you cannot avoid nesting if you need to make use of the first promise's value somewhere down the chain. This is because, if you flatten out the promise chain, you eventually lose the previous promise's returned values.

Ready for the answer? Here you go:

const doSomething = async () => {  const res1 = await p1()  const res2 = await p2()  return p3(res1, res2)}

Can you see the code clarity in the latter code? It is remarkable! Try to use async/await wherever you can, instead ...

Get Learn ECMAScript - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.