0

I have to loop an array, and compute to every element a very heavy task, within several functions, but I need the whole array finished before return the callback. The problem, is that node is not blocking there, is like treating this block of code like asynchronous, cause before it gets done, the callback is returned. What am I missing?

function one(data, callback){
    for(var i=0; i < data.length; i++){
        result = two(data[i]);
    }
    callback(result)
}

function two(data){
        //process
        return three(data);
}

function three(data){
    //heavy task
    return data;
}

callback(result) is called immediately and I need it blocked in order to have the array processed. This was already moved to child process, so it is pretended to work that way.

  • Are you sure you don't have any async code? – Shanoor Jan 12 '16 at 06:17
  • That was exactly what I was missing. In the middle of one of this functions, I was using the async version of readFile. Changed it by readFileSync and everything works fine. Anyway, I took the promises approach to get it cleaner. –  Jan 12 '16 at 14:07

1 Answers1

0
'use strict';
function makePromise(data) {
    return Promise(resolve, reject) {

        //here handle data
        if ( // success ) {
            resolve(result);
        } else {
            reject(error);
        }
    };
}

data.map((element) => makePromise(element))
    .all(restuts => {
        //here results is a array
    })
    .catch(error => {
        console.log(error);
    })

You can use Promise in ES6.

BlackMamba
  • 10,054
  • 7
  • 44
  • 67