Search code examples
javascriptnode.jsloopsforeach

Nodejs callback next loop when function is finished


Supposing we have a script that will execute a certain task for each row in an array.

function execute(err, array){
    loop(array, function(err,object){
         console.log(object)
         //do a certain task when it's finished get into the next object successively.
    });
}

function loop(array,callback){
    array.forEach(function(object){
         callback(null, object);
    });
}

function array(callback){
     callback(null, [1, 2, 3, 4, 5]);
}

setTimeout(function(){
    array(execute); 
}, 6000);

Questions:

  • How to get into the next loop only after finishing the task?
  • Is my function considered asynchronous ?

Solution

  • Try this:

    function execute(err, array) {
        loop(array, function(err, object, next) {
             console.log(object);
             next(); // this will call recur inside loop function
        }, function() {
             console.log('All done');
        });
    }
    
    function loop(array, callback, finish) {
        var copy = array.slice();
        (function recur() {
            var item = copy.shift();
            if (typeof item !== 'undefined') {
                callback(null, item, recur);
            } else if (typeof finish == 'function') { 
                finish();
            }
        })();
    }
    

    No, your function is not asynchronous, but you call it asynchronously using setTimeout.

    EDIT: changed if check

    typeof item !== 'undefined'
    

    so it will work when array contain falsy values like 0 or null.