DEV Community

Discussion on: Explain Async/Await Like I'm Five

Collapse
 
louy2 profile image
Yufan Lou

Because async/await is actually one level higher than Promise. An async function is not a Promise but a () => Promise. In other words, an async function is a lazy Promise.

// Promise
let p0 = new Promise((res, rej) => {
  res(longRunningBlockingTask());
});
p0.then(x => x + 1)
  .then(console.log)
  .catch(console.log)
  .finally(console.log('cleanup'));

Note that we kind of hit a dead-end above. Even though we've created p0 to store the Promise, we cannot rerun p0. The most we can do is attach more thens. We cannot cancel it either.

// async/await
let p = async () => ;
let f = async () => {
  try { console.log(await p()) } catch (err) { console.log(err) }
}
f().catch(console.log)
f().catch(console.log)

We still cannot cancel it, but at least we can rerun it.

A more detailed explanation can be found in the Wiki of Fluture.