If you have multiple promises, an array of promises, and you want to perform an action after they all have resolved you can use Promise.resolve()
.
However if you'd like the same result, whilst having the promises called in order you will need to come up with a custom solution because there is no
api for that.
Let's create a promise factory to generate our promises that we want to execute in sequence:
function createP(id) {
return new Promise((resolve, reject) => {
console.log(id);
const timeout = Math.random() * 100;
setTimeout(() => {
resolve({ id, timeout });
}, timeout);
});
}
The inSequence
function which takes an array of promises as an argument:
function inSequence(promises) {
return promises.reduce((prev, next) => {
return prev.then((prevRes => {
return next.then(nextRes => {
prevRes.push(nextRes); // take the previous result and append the next to it
return prevRes;
});
}));
}, Promise.resolve([]));
}
Usage:
const promises = [
createP(7), createP(5), createP(3)
];
inSequence(promises).then(res => {
console.log(res);
});
Result:
[
{
"id": 7,
"timeout": 56.985111228065755
},
{
"id": 5,
"timeout": 25.835860521855423
},
{
"id": 3,
"timeout": 13.25073904955656
}
]