DEV Community

Anthony "Papa" Santo
Anthony "Papa" Santo

Posted on

Async Await from Beginner to Advanced Features Including Concurrency

Async Await Tutorial


Link to youtube channel: https://www.youtube.com/channel/UC3b871DqOlA5tKbizv4J6mg

What is Async Await?

Async await is used to execute asynchronous tasks in Javascript. The tutorial video above covers Async await and concurrency.

Write Better Code With Concurrency

If you are here to learn async await, watch the video above. Below we will illustrate the power of concurrency!

This is a wait function that returns a promise. The promise resolves in the amount of milliseconds passed to it as an argument.

const wait = (ms) => {
    return new Promise(function(resolve) {
        setTimeout(resolve, ms, 'Message Received');
    });
}

The following function, findMessage(), will await 3 separate asynchronous calls to the wait() function above. Wait is called and 2000 is passed in. This means the promise resolves in 2 seconds. This code takes 6 seconds to execute.

const findMessage = async () => {
  const timeStart = Date.now()
  const one = await wait(2000)
  console.log(one)
  const two = await wait(2000)
  console.log(two)
  const three = await wait(2000)
  console.log(three)
  const timeEnd = Date.now()
  console.log(`Time ${timeEnd - timeStart}`)
}

findMessage()

The following function, findMessageConcurrently(), will await 3 asynchronous calls to the wait() function above. Wait is called and 2000 is passed in. This means the promise resolves in 2 seconds. This code takes just over 2 seconds to execute.

const findMessageConcurrently = async () => {
   const timeStart = Date.now()
   const [one, two, three] = await Promise.all([wait(2000),
 wait(2000), wait(2000)])
   console.log(one)
   console.log(two)
   console.log(three)
   const timeEnd = Date.now()
   console.log(`Time ${timeEnd - timeStart}`)
 }

findMessageConcurrently()

Why?

When using Promise.all, each promise passed in is started. Then it is added to the end of the event loop where a response is awaited. The two second promises can all be done concurrently using Promise.all.

Latest comments (0)