Explaining async/await with promises


Promise

Calling Promise.resolve with a value:

Promise.resolve('value');

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

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

Promise.reject is similar except it’s used when a promise is rejected:

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

Async/Await

Function

A no-op function looks like:

function () {};

Which is similar to the arrow function:

() => {};

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 called, it returns a Promise:

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

Comparison

Fulfilled

Async/await is syntactical sugar for promises:

const promise = Promise.resolve('value');

async () => {
  const result = await promise;
  console.log(result);
};

The above can be transpiled to the following code using promises:

const promise = Promise.resolve('value');

() => {
  promise.then(result => {
    console.log(result);
  });
};

Think of await as the then method in the chain (for a fulfilled promise).

Rejected

Rejected promises are handled with try/catch:

const promise = Promise.reject('reason');

async () => {
  try {
    await promise;
  } catch (error) {
    console.log(error);
  }
};

And the above can be transpiled to the following code using promises:

const promise = Promise.reject('reason');

() => {
  promise.catch(error => {
    console.log(error);
  });
};

The difference here is that the async/await catch looks synchronous even though the code is asynchronous.



If you enjoyed this post, please consider supporting this site!