Created
September 15, 2017 18:49
-
-
Save jakedowns/6657c069a774e7d292f2f872b441658d to your computer and use it in GitHub Desktop.
Sequential Promise Processor : First to Resolve, First to Reject : Simple Helper Methods
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* | |
* Inspired by https://www.abeautifulsite.net/executing-promises-in-sequence-and-stopping-at-the-first-resolved-promise | |
* | |
* Usage: | |
* | |
import * as promise_seq from 'promise-sequence'; | |
return new Promise((resolve, reject)=>{ | |
let ordered_promise_sequence_array = [ | |
some_ordered_method_which_returns_a_promise, | |
another_ordered_method_which_returns_a_promise, | |
a_third_ordered_method_which_returns_a_promise | |
]; | |
promise_seq.first_to_reject(ordered_promise_sequence_array) | |
.then(resolve) | |
.catch(reject); | |
// OR | |
promise_seq.first_to_resolve(ordered_promise_sequence_array) | |
.then(resolve) | |
.catch(reject); | |
}); | |
**/ | |
export const first_to_reject = (seq) => { | |
return new Promise(function (resolve, reject) { | |
// Any left to process? | |
if (seq.length === 0) { | |
// All Resolved! | |
resolve(); | |
} | |
// Try the first promise in the seq. | |
seq[0].call().then(function (val) { | |
// Resolved, remove the first item from the array and recursively | |
// try the next one | |
seq.shift(); | |
first_to_reject(seq).then(resolve).catch(reject); | |
}).catch(function () { | |
// Rejected, fail early, skip the rest of the seq. we're all done! | |
reject.apply(this, arguments); | |
}); | |
}); | |
} | |
export const first_to_resolve = (seq) => { | |
return new Promise(function (resolve, reject) { | |
// Any left to process? | |
if (seq.length === 0) { | |
// All Rejected! | |
reject(); | |
} | |
// Try the first promise in the seq. | |
seq[0].call().then(function () { | |
// Resolved, we're all done! | |
resolve.apply(this, arguments); | |
}).catch(function () { | |
// Rejected, remove the first item from the array and recursively | |
// try the next one | |
seq.shift(); | |
first_to_resolve(seq).then(resolve).catch(reject); | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment