Skip to content

Instantly share code, notes, and snippets.

@pineapplemachine
Created February 1, 2018 08:51
Show Gist options
  • Select an option

  • Save pineapplemachine/b86e061e36763ee5f72401f90d00395d to your computer and use it in GitHub Desktop.

Select an option

Save pineapplemachine/b86e061e36763ee5f72401f90d00395d to your computer and use it in GitHub Desktop.
Resolve a list of promises serially, in order
// Accepts a list of promises. Returns a promise which evaluates each promise
// in the input list serially, waiting for each to resolve before beginning the
// next one. If any promise in the list is rejected, then so is the output
// promise with the same rejection value. If every promise is resolved, then
// the output promise resolves with a list of resolution values.
function resolvePromisesInOrder(promises){
const resultList = [];
const makePromise = (promise, nextPromise) => new Promise((resolve, reject) => {
promise.then(result => {
resultList.unshift(result);
if(nextPromise){
nextPromise.then(resolve).catch(reject);
}else{
resolve(resultList);
}
}).catch(reject);
});
let i = promises.length - 1;
let currentPromise = makePromise(promises[i]);
while(i > 0){
i--;
currentPromise = makePromise(promises[i], currentPromise);
}
return currentPromise;
}
const printA = new Promise((resolve, reject) => {
console.log("A");
resolve("A");
});
const printB = new Promise((resolve, reject) => {
console.log("B");
resolve("B");
});
const printC = new Promise((resolve, reject) => {
console.log("C");
resolve("C");
});
const printD = new Promise((resolve, reject) => {
console.log("D");
resolve("D");
});
/* Console output
A
B
C
D
[ 'A', 'B', 'C', 'D' ]
*/
resolvePromisesInOrder([printA, printB, printC, printD]).then(list => {
console.log(list);
}).catch(error => {
console.error("ERROR!" , error);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment