How to properly use async/await inside a forEach loop in JavaScript?
Hello everyone! I'm new to JavaScript and trying to understand asynchrony. I have an array of URLs, and I want to sequentially load data from each one using `async/await`. I decided to use `forEach`, but I ran into a problem: my code doesn't wait for each request to complete, but starts them all at once.
Here's my code:
```javascript
const urls = ['/api/user/1', '/api/user/2', '/api/user/3'];
async function fetchUserData(url) {
const response = await fetch(url);
return await response.json();
}
async function loadAllUsers() {
urls.forEach(async (url) => {
const userData = await fetchUserData(url);
console.log('User loaded:', userData);
});
console.log('All users loaded!');
}
loadAllUsers();
```
When I run this code, I
No answers yet.
Log in to leave an answer
Blogs
Docker and Swift: Containerizing Applications on iOS and macOS