Created
July 16, 2012 15:24
-
-
Save paulgreg/3123310 to your computer and use it in GitHub Desktop.
Future
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 ); | |
}); |
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');
});
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
You can try that in webconsole on any website having jQuery.