Skip to content

Instantly share code, notes, and snippets.

@mars
Last active August 29, 2015 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mars/0f0d55af678cd878a2d7 to your computer and use it in GitHub Desktop.
Save mars/0f0d55af678cd878a2d7 to your computer and use it in GitHub Desktop.
wrap a Promise with Ruby-esque block behavior; ES6/ES2015
/*
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