Explaining async/await using promises


Promise

Resolve

Calling Promise.resolve with a value:

Promise.resolve('value');

Is the same as instantiating a Promise with a fulfilled value in the callback function:

new Promise(resolve => {
  resolve('value');
});

Reject

Calling Promise.reject with a reason:

Promise.reject('reason');

Is the same as instantiating a Promise with a rejected reason in the callback function:

new Promise((resolve, reject) => {
  reject('reason');
});

Async/Await

Async Function

An async function is declared with async in front of the function:

async function () {};

Which is similar to the async arrow function:

async () => {};

When an async function is invoked, it returns a Promise:

(async () => {})() instanceof Promise; // true

Comparison

Fulfilled

Async/await is the syntactical sugar that makes promises look synchronous (but it’s actually not):

(async () => {
  const result = await Promise.resolve('value');
  console.log(result); // 'value'
})();

This is equivalent to:

Promise.resolve('value').then(result => {
  console.log(result); // 'value'
});

For a fulfilled promise, you can think of await as the then() method in the promise chain.

Rejected

When a promise is rejected inside an async function, you can handle it with a try…catch:

(async () => {
  try {
    await Promise.reject('reason');
  } catch (error) {
    console.log(error); // 'reason'
  }
})();

This is the same thing as:

Promise.reject('reason').catch(error => {
  console.log(error); // 'reason'
});

For a rejected promise, you can think of the catch block as the catch() method in the promise chain.



Please support this site and join our Discord!