Last active
March 30, 2017 18:51
-
-
Save servercharlie/6eafd989ce6011aa7edebd81847fe995 to your computer and use it in GitHub Desktop.
Contextual Promise Chain JS
This file contains hidden or 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
// allows you to use contexts within promise chains. | |
// works best w/ KeyStore where you use your context as your keystore context name / id. | |
// KeyStore.js | a globally reusable value / reference storage | |
// https://gist.github.com/servercharlie/f5b104ceb0bb559e6281b040e6d875e4 | |
// use your own contexts, or use uuid's (like in the provided example) | |
// SimpleUUID.js | an expertly refined generator & validator for UUIDv4. | |
// https://gist.github.com/servercharlie/70638dd74bec7b52223ef9794b47f83c | |
var ContextualPromiseChain = function(_context, _promises){ | |
return new Promise(function (resolve, reject) { | |
function recurse(){ | |
if(_promises.length >= 1){ | |
let _currentPromise = _promises.shift(); | |
_currentPromise(_context) | |
.then(()=>{recurse()}, (reason)=>{reject(reason)}); | |
}else{ | |
resolve(); | |
} | |
} | |
recurse(); | |
}); | |
}; | |
// usage: | |
// tested w/ gulp, just remove the gulp parts if you don't want it. | |
gulp.task(`chain`, () => { | |
var p1 = function(_context){return new Promise(function (resolve, reject) { | |
console.log("Context:", _context); | |
setTimeout(function(){ | |
resolve(); | |
}, 3000); | |
})}; | |
var p2 = function(_context){return new Promise(function (resolve, reject) { | |
console.log("Context:", _context); | |
setTimeout(function(){ | |
resolve(); | |
}, 5000); | |
})}; | |
return ContextualPromiseChain( | |
uuidv4(), | |
[p1, p2] | |
); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment