Created
February 21, 2017 13:07
-
-
Save jaz303/5fcc5fab28e1e4d20a0a32d102ddd683 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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