0

I have a for loop which does many iterations .I would like to put that piece of code in a custom async function as it is blocking.Is there anyway I can write a function so it will call a callback once the loop iteration is over?.

6
  • 1
    If you don't have any non-blocking operations, async will not help you at all. Read blog.slaks.net/2014-12-23/parallelism-async-threading-explained Commented Feb 16, 2015 at 16:19
  • i would change my look for a recursive function and and always defer the next execution to the next tick Commented Feb 16, 2015 at 16:31
  • you may have a look at async library -github.com/caolan/async Commented Feb 16, 2015 at 16:49
  • As SLaks stated this approach is not really useful. If you have a very work intensive Loop there, you could maybe think about extracting it into another NodeJS-Process and call it with the child-process lib. Commented Feb 16, 2015 at 16:49
  • That sounds good, but how do I fork another process?..isnt node single threaded? Commented Feb 16, 2015 at 17:27

1 Answer 1

1

Use asynchronous-function-inside-a-loop paradigm. This ensures that the asynchronous functions get called with the correct value of the index variable.

    var total = someObject.list.length;
    var count = 0;

    for(var i = 0; i < total; i++){
    (function(foo){
    myobj.get(someObject.list[foo], function(err, response) {
        do_something(foo);
        count++;
        if (count > total - 1) done();
    });
    }(i)); //To immediately invoke the function passing 'i' as parameter
    }


    function done() {
    console.log('All data loaded');
    }
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.