There is a point I often face in my node js work and I would like to know the best way to handle it.
I have an asynchronous call to an API that callbacks with a data info, for example a traffic time.
I need to iterate over a collection of data for which i need to get the traffic time. I use async.each to do this.
How can I collect all the traffic times once the requests are all done ?
For now, the solution I am currently working with is passing an additional array argument to the asynchronous call that is an array in which I push the data result and I then callback the array.
I can get all the infos I need in this array once everything is done but, since it is a move I need to do in a lot of different contexts, I would like to know if there is a simpliest way to treat this.
Thank you very much :)
async.map()
works like async.each()
, and allows you to pass a result to the callback. The final callback is then called with an array containing the results.
See https://github.com/caolan/async#map
eg (untested, and could be shorter, but I wrote some stuff explicitly for the example)
async.map(dataCollection, function(data, done) {
trafficTime.get(data, function(err, time) {
if (err) return done(err);
done(null, time);
});
}, function(err, times) {
# times is the results array
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.