WittCode💻

Don't Let Promises Slow Down Your App

By

Don't let JavaScript Promises slow down your application.

Table of Contents 📖

async and await

We can use the keywords async and await to write asynchronous code like synchronous code. In other words, execute a task only after the previous one has completed. For example, the code below has an asynchronous function called wait5Seconds that will wait 5 seconds before returning.

async function wait5Seconds() {
  await new Promise(resolve => setTimeout(resolve, 5000));
  console.log('5 seconds have passed!');
}

async function main() {
  console.log('Starting asynchronous tasks...')
  await wait5Seconds();
  await wait5Seconds();
}

main();

This looks like synchronous code because it is executed one line at a time. Specifically, we have to wait 5 seconds before we can execute the line after the await call.

Promise.all

There isn't anything wrong with the code above but it can easily be sped up using Promise.all.

async function wait5Seconds() {
  await new Promise(resolve => setTimeout(resolve, 5000));
  console.log('5 seconds have passed!');
}

async function main() {
  console.log('Starting asynchronous tasks...')
  await Promise.all([wait5Seconds(), wait5Seconds()]);
}

main();

The JavaScript Promise.all method takes an iterable of promises as input, such as an arry of promises, and returns a single promise when all of the promises in the iterable are fulfilled.

INFO: Promise.all executes multiple asynchronous tasks concurrently. However, as JavaScript is single threaded only one task will be executing at a time. Nevertheless, control can shift between different asynchronous tasks which makes the execution of the tasks provided to Promise.all seem concurrent.

Promise.all Use Case

The Promise.all method is typically used for working with multiple related asynchronous tasks that all need to be fulfilled before continuing code execution. For example, say we need to get data from multiple APIs and then combine them, Promise.all would be a great solution.

Don't Let Promises Slow Down Your App