Skip to content

Instantly share code, notes, and snippets.

@stefanmaric
Created February 12, 2018 13:00
Show Gist options
  • Save stefanmaric/895f51652060a820e2ee7f164af87948 to your computer and use it in GitHub Desktop.
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
/**
* 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