Skip to content

Instantly share code, notes, and snippets.

@domenic
Last active December 20, 2015 00:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save domenic/6039646 to your computer and use it in GitHub Desktop.
Save domenic/6039646 to your computer and use it in GitHub Desktop.
This needs a name
// Needs a clever name like "debounce" or "throttle" (but it's not either of those.)
function doOperationButOnlyReactIfItWasntCalledAgainInBetween(promiseOperation) {
var latestOperation = null;
return function () {
var deferred = Q.defer();
var operation = promiseOperation.apply(this, arguments);
latestOperation = operation;
operation.then(
function (value) {
if (latestOperation === operation) {
deferred.resolve(value);
}
},
function (reason) {
if (latestOperation === operation) {
deferred.reject(reason);
}
}
);
return deferred.promise;
};
}
////////////
var searchThatDoesWhatYouWant = doOperationButOnlyReactIfItWasntCalledAgainInBetween(doSearch);
// User types 'do'
searchThatDoesWhatYouWant('do');
setTimeout(function () {
// 50 milliseconds later, the user types the extra 'g', making it 'dog'
searchThatDoesWhatYouWant('dog');
}, 50);
// Now, imagine that the server returns the results for 'dog' first, then later returns the results for 'do'.
// If we were just using `doSearch`, the results for 'dog' would be replaced with those for 'do', which is
// obviously not what we want. But `searchThatDoesWhatYouWant` does the correct thing, and ignores anything
// but what happens as a result of the latest search, so when the 'do' results come back they are ignored.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment