Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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