Professional Development · Technology

JavaScript’s Async/Await

Introduced in JavaScript standard ES8, async/await offers a new way to handle asynchronous function calls and depreciates callbacks, leading to more readable code. The below example demonstrates how async/await may be used with the ES6 Promise and Promise.all.

Let’s say you have three actions you want to perform

function action1() {
  return new Promise(resolve => {
    setTimeout(() => resolve('This is an action that takes 2 seconds'), 2000); 
  });
}

function action2() {
  return new Promise(resolve => {
    setTimeout(() => resolve('This is an action that takes 5 seconds'), 5000); 
  });
}

function action3() {
  return new Promise(resolve => {
    setTimeout(() => resolve('This is an action that takes 1 second'), 1000); 
  });
}

Of course you won’t actually know when your actions are going to complete, so you’ll have to await them, as so:

async function executeActions() {
  try {
    const [act1, act2, act3] = await Promise.all([action1(), action2(), action3()]);
    console.log(act1 + '\n', act2 + '\n', act3);
  } catch (e) {
    console.error(e);
  }
}

executeActions();

This code uses Promise.all to await the three Promises pending from action 1, 2, and 3, and saves the resolved promise in act1, act2, and act3 using destructuring.

Easy!

Complete code:

function action1() {
  return new Promise(resolve => {
    setTimeout(() => resolve('This is an action that takes 2 seconds'), 2000); 
  });
}

function action2() {
  return new Promise(resolve => {
    setTimeout(() => resolve('This is an action that takes 5 seconds'), 5000); 
  });
}

function action3() {
  return new Promise(resolve => {
    setTimeout(() => resolve('This is an action that takes 1 second'), 1000); 
  });
}
async function executeActions() {
  try {
    const [act1, act2, act3] = await Promise.all([action1(), action2(), action3()]);
    console.log(act1 + '\n', act2 + '\n', act3);
  } catch (e) {
    console.error(e);
  }
}

executeActions();

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s