My question is very similar to this, but I can't get it to work :(
PROBLEM:
I have a Javascript program that needs to run in IE11 and Chrome.
It has a list of functions that I need to execute in order.
Each function returns a Promise.
Promise.all(promisesArray)
works to the extent that I can "wait" until all the functions finish before proceeding. But it DOESN'T guarantee that the functions each run in order. This is essential.I've tried using
Array.prototype.reduce()
, but I haven't been able to figure out how to use it correctly.Because I need to run in IE11, I can't use ES6 features like "arrow functions".
Here is my code:
<script>
var fn = function(arg) {
return new Promise (function (resolve, reject) {
console.log("fn(" + arg + ")...");
resolve("OK");
});
}
var p = fn("A").then(function(r) {
console.log("promise resolved: " + r + ".");
})
var chain = [];
chain.push(fn("3"));
chain.push(fn("1"));
chain.push(fn("2"));
console.log("Built chain:", chain);
Promise.all(chain);
chain.length = 0;
chain[2] = fn("30");
chain[1] = fn("20");
chain[0] = fn("10");
chain.reduce(function(promise, item) {
return promise.then(function() {
console.log("then:", item);
}), Promise.resolve();
});
console.log("Done.");
</script>;
I need the functions to execute in order array[0], array[1], array[2]
.