In the following code I am trying to make multiple (around 10) HTTP requests and RSS parses in one go.
I am using the standard forEach
construct on an array of URIs I need to access and parse the result of.
Code:
var articles;
feedsToFetch.forEach(function (feedUri)
{
feed(feedUri, function(err, feedArticles)
{
if (err)
{
throw err;
}
else
{
articles = articles.concat(feedArticles);
}
});
});
// Code I want to run once all feedUris have been visited
I understand that when calling a function once I should be using a callback. However, the only way I can think of using a callback in this example would be to call a function which counts how many times it has been called and only continues when it has been called the same amount of times as feedsToFetch.length
which seems hacky.
So my question is, what is the best way to handle this type of situation in node.js.
Preferably without any form of blocking! (I still want that blazing fast speed). Is it promises or something else?
Thanks,
Danny
Copyright Notice:Content Author:「dannybrown」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/26268651/node-js-best-way-to-perform-multiple-async-operations-then-do-something-else