Created
February 5, 2019 05:59
-
-
Save skounis/75305189fb22a4b689b7cafa245b98e4 to your computer and use it in GitHub Desktop.
Cancel a Promise
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
// Adapted from: | |
// https://facebook.github.io/react/blog/2015/12/16/ismounted-antipattern.html | |
function cancellable(promise) { | |
let cancelled = false; | |
// Creates a wrapper promise to return. This wrapper is | |
// resolved or rejected based on the wrapped promise, and | |
// on the "cancelled" value. | |
const promiseWrapper = new Promise((resolve, reject) => { | |
promise.then( | |
value => { | |
return cancelled ? reject({ cancelled: true }) : resolve(value); | |
}, | |
error => { | |
return cancelled | |
? reject({ cancelled: true }) | |
: reject(error); | |
} | |
); | |
}); | |
// Adds a "cancel()" method to the promise, for | |
// use by the React component in "componentWillUnmount()". | |
promiseWrapper.cancel = function cancel() { | |
cancelled = true; | |
}; | |
return promiseWrapper; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment