Skip to content

Instantly share code, notes, and snippets.

@domenic
Created June 8, 2016 23:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save domenic/46776bb71a2f885f79013130cd5301aa to your computer and use it in GitHub Desktop.
Save domenic/46776bb71a2f885f79013130cd5301aa to your computer and use it in GitHub Desktop.
"last" with cancelation
"use strict";
var pending = { then: function () {} };
// operation must accept as its first argument a cancel token
// if your operation does not support cancelation, use a shim:
// last((_, ...args) => realOp(...args));
module.exports = operation => {
let latestPromise = null;
let previousCancel = null;
return function () {
if (previousCancel) {
previousCancel();
}
const cancelToken = new CancelToken(c => previousCancel = c);
const promiseForResult = operation.call(this, cancelToken, ...arguments);
latestPromise = promiseForResult;
return promiseForResult.then(
value => {
if (latestPromise === promiseForResult) {
return value;
} else {
cancel throw;
}
},
reason => {
if (latestPromise === promiseForResult) {
throw reason;
} else {
cancel throw;
}
}
);
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment