I am trying to loop through an array of AsynWork to be done. And cant flood the system with async work done all at the time. so I am trying to do one by one with promises. My problem is that I need to go though an array of values so each async works on each value of the array. I managed to do it with this code, but it works for my specific case. Can't make it general. What would be the approach to make it reusable for other type of arrays? I have seen some solutions with array.reduce then promises but cant figure it out. Also have seen examples with Q but not using, if it can be done with simple javascript would be better.
My Code:
function doSomething(ObjIn1, ObjIn2) {
return new Promise(function(resolve, reject) {
console.log("doSomething: ObjIn1: " + ObjIn1 + " ObjIn2: " + ObjIn2);
setTimeout(function() {
console.log("doSomething Done: ObjIn1: " + ObjIn1 + " ObjIn2: " + ObjIn2);
resolve(ObjIn1, ObjIn2);
}, 500);
})
}
function LoopPromises(Function2Loop, functionOptions, Counter, Max) {
console.log("Counter: " + Counter);
if (Counter < Max) {
Function2Loop.apply(this, [functionOptions[0][Counter], functionOptions[1]]).then(function() {
Counter++;
LoopPromises(Function2Loop, functionOptions, Counter, Max);
});
}
}
LoopPromises(doSomething, [
["A1", "A2", "A3"], "ARG2TESTE"
], 0, 3)