Skip to content

Instantly share code, notes, and snippets.

@javimosch
Last active December 2, 2019 13:05
Show Gist options
  • Save javimosch/932e624c9d65e1150b31ed047aa2c810 to your computer and use it in GitHub Desktop.
Save javimosch/932e624c9d65e1150b31ed047aa2c810 to your computer and use it in GitHub Desktop.
Promise sequence in pure javascript (browser and server)
//similar to: https://www.npmjs.com/package/promise-sequential
//input: array of functions that returns a promise
//rules:
//- if one promise fails, the sequence is cancelled and the error is returned (catch)
//returns:
//array of results
function promiseSequence(arr) {
return new Promise(function(resolve, reject) {
var result = [];
var interval = setInterval(function() {
if (result.length === 0) {
var p = arr[0]()
result[0] = p;
p.then(function(res) {
result[0] = res
}).catch(function(err) {
result[0] = err
});
}
var last = result[result.length - 1];
if (!(last instanceof Promise)) {
if (last instanceof Error) {
clearInterval(interval);
return reject(last);
}
if (result.length - 1 == arr.length - 1) {
clearInterval(interval);
resolve(result);
} else {
if (typeof arr[result.length] === 'function') {
var p = arr[result.length]();
result.push(p);
p.then(function(res) {
result[result.length - 1] = res
}).catch(function(err) {
result[result.length - 1] = err
});
}
}
} else {
//wait
}
}, 100);
});
}
/*
//test
var msgs = ['foo', 'bar']
promiseSequence(msgs.map(function(n) {
return function() {
return new Promise(function(resolve, reject) {
setTimeout(function() {
if (n == 'bar') {
return reject(new Error('ups'));
}
resolve(n)
}, 2000)
});
}
})).then(console.info).catch(console.error)
*/
@javimosch
Copy link
Author

If you are reading this today, I recommend this simple snippet instead:

iterable.reduce((p, fn) => p.then(fn), Promise.resolve())

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment