Menu

1 / 13

JavaScript async and await in loops

We’ve moved to freeCodeCamp.org/news - Medium·Zell Liew·8 months ago
#q7UbtRA2
Long article (1989 words) — no AI summary yet.
Reading 0:00
15s threshold

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.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.