Last active
August 29, 2015 14:18
-
-
Save mars/0f0d55af678cd878a2d7 to your computer and use it in GitHub Desktop.
wrap a Promise with Ruby-esque block behavior; ES6/ES2015
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
/* | |
Insert a Promise into a pre-defined Promise chain. | |
@param promiseBlock [Function] takes a Promise | |
parameter & returns the continuation of that parameter. | |
@return [Promise] the fullfilled Promise chain | |
*/ | |
function wrapPromise(promiseBlock) { | |
if (typeof promiseBlock !== 'function') { | |
throw new Error('promiseBlock must be a Function'); | |
} | |
// Set-up source promise and local scope. | |
var sourcePromise = Promise.resolve(); | |
return new Promise((resolve, reject) => { | |
var resultPromise = promiseBlock(sourcePromise); | |
if (!resultPromise || typeof resultPromise.then !== 'function') { | |
throw new Error('promiseBlock must return a Promise'); | |
} | |
return resultPromise | |
.then((v) => { | |
// clean-up | |
resolve(v); | |
}) | |
.catch((error) => { | |
// clean-up | |
reject(error); | |
}) | |
}) | |
.catch((error) => { throw error }); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment