I have a function called fetchCourseCode(string)
that fetches some information from a web server and stores them in to array. I also have ~135 course codes (strings) that should be fetched in discrete times with same period.
Normally, in a non-asynchronous situation, the code should be:
for (eachCode of COURSE_CODES) {
fetchedInformationArray.push(fetchCourseCode(eachCode));
}
However, as this is a time taking operation, node.js event loop escapes to the fetchCourseCode()
's return and we got nothing (an array of undefined
s) in the end.
So I tried to use async
's forEachOf
function to iterate over array, having constructed a promise manually to the fetchCourseCode()
function:
async.forEachOf(kCOURSE_CODES, function(value, key, callback) {
console.log("fetched " + value);
fetchCourseCode(value).then(response) {
schedule[key] = response;
callback();
}, function(error) {
callback(error);
});
}, function(error) {
if (error) {
console.error(error);
} else {
console.log("Fetched schedule: " + JSON.stringify(schedule));
}
});
Unfortunately I found out it is said that using nested promises is an anti-pattern.
I am -desperately thinking of being- not able to use Q.all()
, because the list of functions is dynamically changing. Also, async.map
couldn't help me: Callback function is not called strangely.
I haven't got to understanding of node's event loop, being pretty new in these lands.