Skip to content

Instantly share code, notes, and snippets.

@softwarespot
Last active November 5, 2017 21:23
Show Gist options
  • Save softwarespot/64b8b010c1a66cf187834cb3f67599b5 to your computer and use it in GitHub Desktop.
Save softwarespot/64b8b010c1a66cf187834cb3f67599b5 to your computer and use it in GitHub Desktop.
Promise.if implementation
/**
* Resolve or reject a {@link Promise|Promise} based on the return value of a function.
* If a truthy value is returned, then the {@link Promise|Promise} is
* resolved with the truthy value; otherwise, if a falsy value, it's rejected with the reason
* defined as an instance of Error
*
* @memberof Promise
* @param {Function} fn Function to invoke and compare the return value of
* @param {*} [comparison] Optional comparison value to compare with the return value of the function;
* otherwise, default to truthy/falsy comparison
* @param {*} [initial] Optional initial value to pass to the function
* @returns {Promise} A {@link Promise|Promise} that is either resolved with the function's return value;
* otherwise, it's rejected with the reason defined as an instance of Error
*/
Promise.if = (fn, comparison, initial) => {
const hasComparisonArg = comparison !== undefined;
return new Promise((resolve, reject) => {
const result = fn(initial);
const isTruthy = hasComparisonArg ? comparison === result : Boolean(result);
if (isTruthy) {
resolve(result);
} else {
const err = new Error(`Invalid Promise if outcome, result: "${result}"${hasComparisonArg ? `, comparison: "${comparison}"` : ''}`);
reject(err);
}
});
};
/**
* Resolve or reject a {@link Promise|Promise} based on the return value of a function.
* If a truthy value is returned, then the {@link Promise|Promise} is
* resolved with the truthy value; otherwise, if a falsy value, it's rejected with the
* reason defined as an instance of Error.
*
* @memberof Promise
* @param {Function} fn Function to invoke and compare the return value of
* @param {*} [comparison] Optional comparison value to compare with the return value of the function;
* otherwise, default to truthy/falsy comparison
* @returns {Promise} A {@link Promise|Promise} that is either resolved with the function's return value;
* otherwise, it's rejected with the reason defined as an instance of Error
*/
Promise.prototype.if = function (fn, comparison) {
return this.then(value => Promise.if(fn, comparison, value));
};
// Example(s)
Promise.if(() => 1092)
.then(result => {
console.log('Success::', result);
})
.catch(err => {
console.error('Error::', err);
});
Promise.resolve(Math.floor(Math.random() * 2000))
.if(value => {
console.log('Random number:', value);
return value % 2 === 0;
})
.then(result => {
console.log('Success::', result);
})
.catch(err => {
console.error('Error::', err);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment