I need to execute dynamically a function for all items of an array, but Array.forEach
execute in sequence and I need execute in asynchronous.
items.forEach(function(item) {
doSomething(item);
});
I try this:
var promises = [];
items.forEach(function(item) {
var promise = function() {
return Q.fcall(function() {
doSomething(item);
});
};
promises.push(promise());
});
Q.all(promises).then(function () {
otherFunction(datacontext.mainList); //use datacontext.mainList filled.
});
But the execution is always in sequence and I need the execution in parallel.
The doSomething(item)
method:
function doSomething(item) {
var children = getChildren(item); //get data from local with manager.executeQueryLocally
var total = getTotal(children); //simple calculations
datacontext.mainList.push({
name: item.firstName() + ' ' + item.lastName(),
total: total
});
}
Please help me.