Skip to content

Instantly share code, notes, and snippets.

@barneycarroll
Last active April 24, 2018 02:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save barneycarroll/0a0d4eb45c35161b4d34858a8d422c50 to your computer and use it in GitHub Desktop.
Save barneycarroll/0a0d4eb45c35161b4d34858a8d422c50 to your computer and use it in GitHub Desktop.
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