JavaScript JavaScript async and await in loops
Zell Liew
8 min readMay 21, 2019
--
Basic async and await is simple. Things get a bit more complicated when you try to use await in loops.
In this article, I want to share some gotchas to watch out for if you intend to use await in loops.
Before you begin
I'm going to assume you know how to use async and await . If you don't, read the previous article to familiarize yourself before continuing.
Preparing an example
For this article, let's say you want to get the number of fruits from a fruit basket.
const fruitBasket = {
apple: 27,
grape: 0,
pear: 14
};
You want to get the number of each fruit from the fruitBasket. To get the number of a fruit, you can use a getNumFruit function.
const getNumFruit = fruit => {
return fruitBasket[fruit];
};const numApples = getNumFruit(“apple”);
console.log(numApples); // 27
Now, let's say fruitBasket lives on a remote server. Accessing it takes one second. We can mock this one-second delay with a timeout.…