You can ditch async
altogether and go for async/await
quite easily.
Promisify your request and use async/await
Just turn request
into a Promise
so you can await
on it.
Better yet just use request-promise-native that already wraps request using native Promises.
Serial example
From then on it’s a slam dunk with async/await
:
const rp = require('request-promise-native')
const users = [1, 2, 3, 4]
const results = []
for (const idUser of users) {
const result = await rp('http://foo.com/users/' + idUser)
results.push(result)
}
Parallel example
Now, the problem with the above solution is that it’s slow – the requests run serially. That’s not ideal most of the time.
If you don’t need the result of the previous request for the next request, just go ahead and do a Promise.all
to fire parallel requests.
const users = [1, 2, 3, 4]
const pendingPromises = []
for (const idUser of users) {
// Here we won't `await` on *each and every* request.
// We'll just prepare it and push it into an Array
pendingPromises.push(rp('http://foo.com/users/' + idUser))
}
// Then we `await` on a a `Promise.all` of those requests
// which will fire all the prepared promises *simultaneously*,
// and resolve when all have been completed
const results = await Promise.all(pendingPromises)
Error handling
Error handling in async/await
is provided by plain-old try..catch
blocks, which I’ve omitted for brevity.