Avatar ·

How to properly use async/await inside a forEach loop in JavaScript?

Hello everyone! I started learning asynchronous JavaScript and encountered a problem that completely baffled me. I have an array of URLs, and I want to sequentially load data from each one using `fetch` and `async/await`. I wrote this code: ```javascript const urls = ['https://api.example.com/data/1', 'https://api.example.com/data/2', 'https://api.example.com/data/3']; async function fetchUrls() { urls.forEach(async (url) => { const response = await fetch(url); const data = await response.json(); console.log('Loaded:', data); }); console.log('All requests sent!'); } fetchUrls(); ``` I expected that data from the first URL would load first, then from the second, then from the third, and only after that the message "All requests sent!" would be printed.