Skip to content

Instantly share code, notes, and snippets.

@egorguscha
Created November 7, 2018 12:51
Show Gist options
  • Save egorguscha/fbbde1efe65c00e5fed63af535bbe538 to your computer and use it in GitHub Desktop.
Save egorguscha/fbbde1efe65c00e5fed63af535bbe538 to your computer and use it in GitHub Desktop.
async function updateUser(token) {
let cancelled = false;
// we don't reject, since we don't have access to
// the returned promise
// so we just don't call other functions, and reject
// in the end
token.cancel = () => {
cancelled = true;
};
const data = await wrapWithCancel(fetchData)();
const userData = await wrapWithCancel(updateUserData)(data);
const userAddress = await wrapWithCancel(updateUserAddress)(userData);
const marketingData = await wrapWithCancel(updateMarketingData)(userAddress);
// because we've wrapped all functions, in case of cancellations
// we'll just fall through to this point, without calling any of
// actual functions. We also can't reject by ourselves, since
// we don't have control over returned promise
if (cancelled) {
throw { reason: 'cancelled' };
}
return marketingData;
function wrapWithCancel(fn) {
return data => {
if (!cancelled) {
return fn(data);
}
}
}
}
const token = {};
const promise = updateUser(token);
// wait some time...
token.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