Last active
November 2, 2022 21:38
-
-
Save greggman/0b6eafb335de4bbb557c to your computer and use it in GitHub Desktop.
Run promises in sequence until one succeeds
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
var Promise = require('promise'); | |
// A function returns a function that will generates a promise when called. | |
// It will wait 1 second before fulfilling or rejecting the promise. Second argument f = true mean "fail!" | |
var fn = function(v, f) { | |
return function() { | |
return new Promise(function(fulfill, reject) { | |
setTimeout(function() { | |
console.log(new Date()); | |
console.log(v); | |
if (f) { | |
reject(); | |
} else { | |
fulfill(); | |
} | |
}, 1000); | |
}); | |
}; | |
}; | |
// array of functions that create and return a promise. | |
// Promises start executing on creation therefore you put the promises in a sequence. You have to put | |
// functions to create them in a sequence | |
// 1 will fail, 2 will fail, 3 will succeed, 4 and 5 would succeed but will be skipped | |
var tasks = [fn(1, true), fn(2, true), fn(3), fn(4), fn(5)]; | |
var skip = function() { | |
console.log("skip"); | |
}; | |
// This works because when reduce is called with a second argument | |
// the first pass through the function it will be passed that second | |
// argument. So in this case the first time function is called it's | |
// passed the Promise.reject() promise. `cur` will be that rejected | |
// promise so `cur.then(skip, next) will call next. next time through | |
// the loop cur is the first Promise that was just created. It hasn't | |
// finished yet so calling then just registers what to do when it does | |
// finish. once one succeeds they'll all end up calling skip instead of | |
// the remaining functions that generate promises. | |
tasks.reduce(function(cur, next){ | |
return cur.then(skip, next); | |
}, Promise.reject()).then(function(){ | |
console.log("done"); | |
}, function() { | |
console.log("failed"); | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment