Member-only story
Concurrent Requests in Node.js (Javascript) using Async/Await
Looking for a great (remote only) React Dev? Visit my profile on LinkedIn and say hi! 😃
To make concurrent asynchronous requests in NodeJS (Javascript), we can take advantage of the setTimeout function and use it together with async/await, plus trusty old count.
What we are aiming for here is that 3 requests get sent asynchronously, but the promise they’re contained in only resolves when ALL 3 have returned. If it takes too long, we want to reject the promise, since the data has likely become stale.
Originally I tried using Promise.all(), but ran into problems with it. The following implementation worked MUCH better for me.
const makeRequest = () => {
const p = new Promise((resolve, reject) => {
setTimeout(() => resolve('hello'), 1000)
}) p.catch(err => console.log(err))
return p
}const makeConcurrentRequests = endpoints => {
const p = new Promise((resolve, reject) => { let results = []
let count = 0 setTimeout(async() => {
results[0] = await makeRequest(endpoints[0])
count++
console.log('Result 1:', results[0])
}) setTimeout(async() => {
results[1] = await…