DEV Community

Cover image for How I've been misusing Async Await
Arpan Kc
Arpan Kc

Posted on • Edited on

How I've been misusing Async Await

Async-await is very intuitive and apparently very easy to misuse. Recently I've found out how I've been misusing this feature because of which my JS executes a lot slower than it should.

Let's look at the example to demonstrate what the problem was:

How I used to do it:

// Fetching promises one after the other, blocking execution

const getItems = async() =>{ 
    const itemA = await fetch("http://url.com/itemA");
    const itemB = await fetch("http://url.com/itemB");

    return [itemA, itemB]
}


How the pros do it:

// Fetching multiple promises concurrently to avoid delaying program

const getItems = async() =>{ 
    const itemA = fetch("http://url.com/itemA");
    const itemB = fetch("http://url.com/itemB");

    const items = await Promise.all([itemA,itemB]);
    return items;
}

See the core difference is how I was previously waiting for itemA to resolve before fetching itemB. On the other hand, when I wait for both the promises to resolve concurrently I speed up the execution by not having itemA to resolve before itemB.

(Note: However this is only recommended when the itemB does not somehow depend upon the promise from itemA being resolved first.)

P.S. Please follow me on twitter, I'd really appreciate it. @Nipeshkc

Top comments (4)

Collapse
 
nappy profile image
nappy • Edited

Basically async/await allows you to write asynchronous code the same way as synchronous code. Synchronous code inherently does not allow parallelism though. So unfortunately teaching how async/await works is not really a good introduction to asynchronous programming. I would recommend starting with functional reactive libraries like rxjs.

Collapse
 
avalander profile image
Avalander

I mean, your function could be shortened to get rid of async/await altogether in this case.

const getItems = () => Promise.all([
  fetch('http://url.com/itemA'),
  fetch('http://url.com/itemB'),
])

In most cases you don't really need to declare an intermediate variable to hold a promise when you want to run stuff in parallel, you can just create the promise within a Promise.all.

Collapse
 
nipeshkc7 profile image
Arpan Kc

Thanks for the feedback, Avalander ! I will definitely incorporate these changes into the post.

Collapse
 
pedrovrima profile image
Pedro Martins

Nice tip! Thanks Arpan!