I have a dynamic number of promises that I need to run sequentially. I understood how I can run sequentially promises but I don't succeed to make it dynamic with a number of promises that could vary.
Here is a way I found to do it statically How to resolve promises one after another? :
function waitFor(timeout) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
resolve(`Finished waiting ${timeout} milliseconds`);
}, timeout);
});
}
waitFor(1000).then(function(result) {
$('#result').append(result+' @ '+(new Date().getSeconds())+'<br>');
return waitFor(2000);
}).then(function(result) {
$('#result').append(result+' @ '+(new Date().getSeconds())+'<br>');
return waitFor(3000);
}).then(function(result) {
$('#result').append(result+' @ '+(new Date().getSeconds())+'<br>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div id="result"></div>
I would like to do the same but instead of 3 nested promises, I would like to have any number I want. Can you help me ?
Thanks a lot!!
There are three basic ways to achieve this task with Promises.
.reduce()
pattern.The
scanl
pattern would sequence promises one after another but once it is completed you also have access to the interim promise resolutions. This might be useful in some cases. If you are going to construct an asynchronous tree structure lazily (branching from the nodes only when needed) you need to have access to the previous promise resolutions.In order to achieve
scanl
functionality in JS, first we have to implement it.we feed
scanl
withxs
which is the array of timeouts in this particular example,f
which is a callback function that takesacc
(the accumulator) ande
(current item) and returns the new accumulator. Accumulator values (the interim promise resolutions) are mapped over the timeouts array to be accessed when needed.Make a seprate function to handle the number of iterations
If you don't care for serialization, you can use Promise.all https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
Or, you can use an async function:
Forget I commented (when you convert a Promise to Observable or include the promise in an array, the Promise is executed). You can use a "recursive" function