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)
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 howasync/await
works is not really a good introduction to asynchronous programming. I would recommend starting with functional reactive libraries likerxjs
.I mean, your function could be shortened to get rid of
async/await
altogether in this case.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
.Thanks for the feedback, Avalander ! I will definitely incorporate these changes into the post.
Nice tip! Thanks Arpan!