The following code simulates multiple async HTTP requests using a for loop in node.
// Simulation of HTTP call that returns a promise after ms milliseconds
const waitFor = (ms) => new Promise(r => setTimeout(r, ms));
// Http requests array
const httpRequests = [
{ id: 1, url: 'http://call-111.com', time: 20000 },
{ id: 2, url: 'http://call-222.com', time: 10000 },
{ id: 3, url: 'http://call-333.com', time: 5000 }
];
// Loop function
function makeRequests(httpRequests) {
for (let request of httpRequests) {
makeAsyncRequest(request);
}
console.log('All request done!!! waiting response....');
}
// Async HTTP calls
async function makeAsyncRequest(request) {
console.log(`${new Date().toISOString()} - making ${request.id} http call to ${request.url}`);
await waitFor(request.time);
console.log(`${new Date().toISOString()} - finishing ${request.id} http call to ${request.url}`);
}
// Run
makeRequests(httpRequests);
To execute the code create a file with the following name async_for_loop.js
and copy the code above, after that run in the terminal the following command:
node async_for_loop.js
The output will be something like the messages below:
2018-09-25T12:58:01.734Z - making 1 http call to http://call-111.com
2018-09-25T12:58:01.736Z - making 2 http call to http://call-222.com
2018-09-25T12:58:01.737Z - making 3 http call to http://call-333.com
All request done!!! waiting response....
2018-09-25T12:58:06.741Z - finishing 3 http call to http://call-333.com
2018-09-25T12:58:11.737Z - finishing 2 http call to http://call-222.com
2018-09-25T12:58:21.745Z - finishing 1 http call to http://call-111.com
Note in the console messages that the for loop executes without wait (block the code) the "HTTP response" of the requests, and also note that the first request made takes more time to return, for this reason it finishes after all other request.