Created
June 26, 2017 21:26
-
-
Save kimhogeling/a88d6d3fa5014f002d55956aa6f6dd9d to your computer and use it in GitHub Desktop.
Create a promise with a guard and an external resolver for performing some tasks before resolving
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
/** | |
* Save some data | |
*/ | |
const persistData = data => { | |
// persist the data | |
}; | |
/** | |
* Fetch some data, persist it and resolve a promise by given resolve function. | |
* | |
* @param {function} resolve - Some resolve from some Promise | |
* @return {Promise} - A promise from the fetch api | |
*/ | |
const fetchAndPersistAndResolve = resolve => | |
fetch('url') | |
.then(data => { | |
persistData(data.json()); | |
resolve(); | |
}); | |
/** | |
* This function is passed below to the promise creator, so it becomes the promise's guard | |
* | |
* @return {boolean} | |
*/ | |
const checkSomething = () => true; | |
/** | |
* Create a promise which uses a given guard and a given external resolver | |
* | |
* @param {function} guard - A guard that returns a boolean, false if the promise needs to be rejected | |
* @param {function} externalResolver - An external function, performs other tasks before resolving the promise | |
*/ | |
const createPromiseWithGuardAndExternalResolver = (guard, externalResolver) => | |
new Promise((resolve, reject) => { | |
if (!guard()) { | |
reject(); | |
// TODO: not sure, if this return statement is necessary | |
return; | |
} | |
externalResolver(resolve) | |
.catch(reject); | |
}); | |
const p = createPromiseWithGuardAndExternalResolver(checkSomething, fetchAndPersistAndResolve); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment