How should I write my recursive loop to correctly execute promises in order? I've tried with Promise.all(Array.map(function(){})); which does not suit my needs as those steps need to be ran in a sequence. I've tried with a custom promise for I've found here, but it also has problems.
The promise for:
var promiseFor = (function(condition, action, value) {
var promise = new Promise(function(resolve, reject) {
if(!condition(value)) {
return;
}
return action(value).then(promiseFor.bind(null, condition, action));
});
return promise;
});
The problem with this for is that it seems to stop at the deepest recursive call, not returning to continue executing the loop to finish correctly.
For example: in PHP a code like this:
function loopThrough($source) {
foreach($source as $value) {
if($value == "single") {
//do action
} else if($value == "array") {
loopThrough($value);
}
}
}
If i pass lets say a folder structure and "single" means file, it will print all files. But the promise for I'm using stops at the first dead end.
EDIT: Added bluebird to see if it could help with anything, still the same thing. Here's the current loop code
var runSequence = (function(sequence, params) {
return Promise.each(sequence, function(action) {
console.log(action['Rusiavimas'] + ' - ' + action['Veiksmas']);
if(params.ButtonIndex && params.ButtonIndex != action['ButtonIndex']) {
return Promise.resolve();
}
if(action['Veiksmas'].charAt(0) == '@') {
var act = action['Veiksmas'];
var actName = act.substr(0, act.indexOf(':')).trim();
var actArg = act.substr(act.indexOf(':')+1).trim();
/* This one is the code that figures out what to do and
also calls this function to execute a sub-sequence. */
return executeAction(actName, actArg, params);
} else {
sendRequest('runQuery', action['Veiksmas']);
}
});
});
I have 3 sequences, each consisting of 5 actions. First and second sequence has the next sequence as it's third action. Here's the result I get (numbers mean which sequence):
1 - @PirmasVeiksmas
1 - @AntrasVeiksmas
1 - @Veiksmas: list_two
2 - @PirmasVeiksmas
2 - @AntrasVeiksmas
2 - @Veiksmas: list_three
3 - @PirmasVeiksmas
3 - @AntrasVeiksmas
3 - @TreciasVeiksmas
3 - @KetvirtasVeiksmas
3 - @PenktasVeiksmas
As you can see it enters the next sequence and continues like it should, but once the third one is complete, it should resume the second sequence and finish up with the first one. But it stops as soon as it hits the first dead end in recursion.
EDIT2: Codepen example of what I have now and with visual representation of what's happening: Codepen link
Output should be:
fa1
second
sa1
third
ta1
ta2
ta3
sa3
fa3