Skip to content

Instantly share code, notes, and snippets.

@paulgreg
Created July 16, 2012 15:24
Show Gist options
  • Save paulgreg/3123310 to your computer and use it in GitHub Desktop.
Save paulgreg/3123310 to your computer and use it in GitHub Desktop.
Future
var future = function(expectedCalls, action) {
var counter = 0;
return function() {
counter++;
if (counter === expectedCalls) action();
}
}
var products = [ {id:1}, {id:2}, {id:3}, {id:4}, {id:5} ];
var notify = future(products.length, function() {
alert('everything is saved');
});
products.forEach(function(product) {
$.post("/save", product, function() {})
.complete( notify );
});
@paulgreg
Copy link
Author

You can try that in webconsole on any website having jQuery.

@dharFr
Copy link

dharFr commented Jul 16, 2012

Nice!
jQuery's Deferred Objects also provide a nice way of doing this:

var products = [ {id:1}, {id:2}, {id:3}, {id:4}, {id:5} ];

var requests = $.map(products, function(val, i) {
  return $.post("/echo/json/", val)
});
$.when(requests).done(function(){
  alert('everything is saved');
});

@paulgreg
Copy link
Author

Thx @dharFr !
Yes, you’re totally right but it’s always cool to "find" those kind of patterns yourself ! :-)
And it’s nice that It takes only a few lines of code.
JavaScript, FTW !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment