How to return from async loops in Node.js
-
21-06-2021 - |
Question
When using async library for flow control, specifically async.forEach how do you properly perform a callback in case when you need to skip a specific item.
Example:
async.forEach(bigCollection, function(item, callback) {
if(skipThis) {
return callback();
// OR BELLOW IS BETTER??
//return process.nextTick(callback);
}
db.query(query, callback);
}, callback);
In case that I don't use process.nextTick(callback)
do I risk running into stack overflow if the bigCollection is too big? And in case that I do use process.nextTick(callback)
do I anyhow sabotage my code?
I have got into habit of doing it the process.nextTick(callback)
way, however I am not so sure it's a good practice to do so.
Solution
I would say that without nextTick it's ok.
async.forEach(bigCollection, function(item, callback) {
if(skipThis) {
return callback();
}
db.query(query, callback);
}, callback);
If bigCollection is too big, then you will get the overflow before you come into the loop.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow