Created
February 12, 2018 13:00
-
-
Save stefanmaric/895f51652060a820e2ee7f164af87948 to your computer and use it in GitHub Desktop.
Javascript ES6 defer function to create deferred Promises with extra resolve and reject methods
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
/** | |
* Create an new deferred promise that can be resolved/rejected from outside. | |
* @return {Promise} A new Promise with two extra methods: resolve and reject. | |
* | |
* @example | |
* const unknownResult = () => { | |
* const deferredPromise = defer() | |
* | |
* const errorTimeoutId = setTimeout( | |
* () => { | |
* clearTimeout(successTimeoutId) | |
* deferredPromise.reject(new Error('Error!')) | |
* }, | |
* Math.round(Math.random() * 1e4) | |
* ) | |
* | |
* const successTimeoutId = setTimeout( | |
* () => { | |
* clearTimeout(errorTimeoutId) | |
* deferredPromise.resolve('Success!') | |
* }, | |
* Math.round(Math.random() * 1e4) | |
* ) | |
* | |
* return deferredPromise | |
* } | |
* | |
* unknownResult() | |
* .then(console.log) | |
* .catch(console.error) | |
*/ | |
const defer = () => { | |
const bag = {} | |
return Object.assign( | |
new Promise((resolve, reject) => Object.assign(bag, { resolve, reject })), | |
bag | |
) | |
} | |
export default defer |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment