1

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.

1
  • 1
    Stack overflow? Why would you run into that? I don't see a reason why first solution would cause that and second not. On the other hand if your collection is really big, then stop thinking about semi-solutions and just partition it into smaller pieces and process piece by piece (you can for example wrap everything into async.series and run async.forEach in every piece). Commented Jul 19, 2012 at 11:19

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.