Skip to content

Instantly share code, notes, and snippets.

@jaz303
Created February 21, 2017 13:07
Show Gist options
  • Save jaz303/5fcc5fab28e1e4d20a0a32d102ddd683 to your computer and use it in GitHub Desktop.
Save jaz303/5fcc5fab28e1e4d20a0a32d102ddd683 to your computer and use it in GitHub Desktop.
module.exports = function(cb) {
let state = 'idle', cancel = null, pending = null;
function submit(promise) {
let cancelled = false;
promise.then((res) => {
if (!cancelled) {
cb(res);
oncomplete();
}
});
return () => { cancelled = true; };
}
function oncomplete() {
switch (state) {
case 'idle':
console.error("oncomplete() called in idle state, this should never happen");
break;
case 'working':
cancel = null;
state = 'idle';
break;
case 'pending':
cancel = submit(pending);
pending = null;
state = 'working';
break;
}
}
return {
run(promise) {
switch (state) {
case 'idle':
cancel = submit(promise);
state = 'working';
break;
case 'working':
case 'pending':
pending = promise;
state = 'pending';
break;
}
},
clear() {
if (cancel) {
cancel();
cancel = null;
}
pending = null;
state = 'idle';
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment