Member-only story

Concurrent Requests in Node.js (Javascript) using Async/Await

Ben Grunfeld
2 min readAug 13, 2018

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…

--

--

Ben Grunfeld
Ben Grunfeld

Written by Ben Grunfeld

I’m a Front End Engineer who loves React, NextJS, and GraphQL. Looking for a developer in #Israel? Contact me at: https://www.linkedin.com/in/bengrunfeld/

No responses yet