Skip to content

Instantly share code, notes, and snippets.

@prashcr
Created December 9, 2015 23:31
Show Gist options
  • Save prashcr/45d0eda2b1452d76779f to your computer and use it in GitHub Desktop.
Save prashcr/45d0eda2b1452d76779f to your computer and use it in GitHub Desktop.
// 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