I have list of data which is in array format for example:
var resultArray = ['a','b','c','d','e'];
I have used this array iteration in my code like this:
var updateArray = [];
_.each(resultArray, function (value, index) {
//execute this function for file uploading..
processMyFunction(value, function (error, success) {
if(error) {
//code to push it in my new array list
updateArray.push({value:value,message:error});
}
else {
//code to push it in my new array list
updateArray.push({value:value,message:error});
}
});
console.log(updateArray)
});
Here it does not gives me updated console. As uploading function takes time to do it’s action and it come out from this processMyFunction function. How should i make this _.each to wait until my function does not complete it’s process?
Any suggestion on that?
This can not work since processMyFunction
seems asynchronous, which means the it will be done iterating over resultArray
possibly before any function as returned a result.
Instead of _.each you will need to process the resultArray from within the callback of the processMyFunction
Iterate using functions, below is an example. There are also a multitude of async libraries that can help, like this .each function: http://caolan.github.io/async/docs.html#each
var resultArray = ['a','b','c','d','e'];
var updateArray = [];
function runSomeCalculation(index){
// All done
if(index >= resultArray.length){
console.log(updateArray);
return true;
}
processMyFunction(resultArray[index], function (error, success){
if(error) {
//code to push it in my new array list
updateArray.push({value:value,message:error});
runSomeCalculation(index+1);
}
else {
//code to push it in my new array list
updateArray.push({value:value,message:error});
runSomeCalculation(index+1);
}
});
};
// Start first iteration
runSomeCalculation(0);