Created
December 9, 2015 23:31
-
-
Save prashcr/45d0eda2b1452d76779f 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
// https://github.com/bjoerge/promise-latest | |
window.latest = latest; | |
function latest(fn) { | |
let lastAdded | |
let pending | |
let resolve | |
let reject | |
return function (...args) { | |
// in the future if/when promises gets cancellable, we could abort the previous here like this | |
// lastAdded.cancel() | |
lastAdded = fn(...args) | |
if (!pending) { | |
pending = new Promise((_resolve, _reject) => { | |
resolve = _resolve | |
reject = _reject | |
}) | |
} | |
lastAdded.then(fulfill.bind(null, lastAdded), fail.bind(null, lastAdded)) | |
return pending | |
} | |
function fulfill(promise, value) { | |
if (promise === lastAdded) { | |
pending = null | |
resolve(value) | |
} | |
} | |
function fail(promise, error) { | |
if (promise === lastAdded) { | |
pending = null | |
reject(error) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment