Skip to content

Instantly share code, notes, and snippets.

@jribble
Last active August 29, 2015 14:20
Show Gist options
  • Save jribble/5ada96c6b8fe00f026a2 to your computer and use it in GitHub Desktop.
Save jribble/5ada96c6b8fe00f026a2 to your computer and use it in GitHub Desktop.
compare promise vs boolean based async call duplication prevention
// async lock using promise
// this queues all calls
var pending = Q.when(true);
function callToServer() {
pending = pending.then(function() {
return callService("myService", params);
});
}
// async avoid double call using flag
// this skips any calls made while the a call is pending
var running = false;
function callToServer() {
if(!running) {
running = true;
return callService("myService", params)
.then(function(result) {
running = false;
return result;
});
}
}
// I guess you could duplicate the skip behavior with a promise like this
var pending = Q.when(true);
function callToServer() {
if(!pending.isPending()) {
pending = callService("myService", params);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment