DEV Community

Anthony Santonocito
Anthony Santonocito

Posted on

30 6

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');
    });
}
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay