Create a gist now

Instantly share code, notes, and snippets.

Embed
Of many sequential promises, only the last is worthy of consequence

There are many scenarios where a particular interaction makes repeated calls to an asynchronous, and each subsequent call invalidates the previous. For example, typing in a field which can query an HTTP service for insights: if I type 'a', and wait long enough, a call should be sent to ask for pertinent suggestions; but if I'm still waiting on that response when I type 'b', then the results of the last call are impertinent. Only the last call's response should resolve.

Calling latest creates a 'promise debouncer' function. Either you pass in the async function there and then and call it without arguments, or you instantiate it empty and pass in the async function upon request. In either case, calling the function before its last promise has resolved will ensure that promise never resolves: only the last request will ever resolve.

export default = maybeThis => {
let it
return (orThat = maybeThis) => {
const promise = it = orThat()
return new Promise(resolve => {
promise.then(result => {
if(promise === it)
resolve(result)
})
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment