Created
December 11, 2017 14:33
-
-
Save Anenth/ee1d230876df26480bde5191d6a4fb7f to your computer and use it in GitHub Desktop.
Cancellable promise with bluebird
This file contains 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
import Promise from 'Bluebird'; | |
function updateUser() { | |
return new Promise((resolve, reject, onCancel) => { | |
let cancelled = false; | |
// you need to config Bluebird to have cancellation | |
// http://bluebirdjs.com/docs/api/promise.config.html | |
onCancel(() => { | |
cancelled = true; | |
reject({ reason: 'cancelled' }); | |
}); | |
return fetchData() | |
.then(wrapWithCancel(updateUserData)) | |
.then(wrapWithCancel(updateUserAddress)) | |
.then(wrapWithCancel(updateMarketingData)) | |
.then(resolve) | |
.catch(reject); | |
function wrapWithCancel(fn) { | |
// promise is resolved only with one parameter | |
return (data) => { | |
if (!cancelled) { | |
return fn(data); | |
} | |
}; | |
} | |
}); | |
} | |
const promise = updateUser(); | |
// wait some time... | |
promise.cancel(); // user will be updated any way |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment