Skip to content

Instantly share code, notes, and snippets.

@Anenth
Created December 11, 2017 14:33
Show Gist options
  • Save Anenth/ee1d230876df26480bde5191d6a4fb7f to your computer and use it in GitHub Desktop.
Save Anenth/ee1d230876df26480bde5191d6a4fb7f to your computer and use it in GitHub Desktop.
Cancellable promise with bluebird
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