4 ms·
Or you can make a count-down latch of some kind: var num_results = 3; var results = [] var makeCallback = function(index) { return function(response)
by Groxx 13y ago
Or you can make a count-down latch of some kind:
var num_results = 3;
var results = []
var makeCallback = function(index) {
return function(response) {
num_results -= 1;
results[index] = response;
if (num_results > 0) {
return;
}
// actually do stuff here, all results are loaded.
};
};
$.get("/a", makeCallback(0));
$.get("/b", makeCallback(1));
$.get("/c", makeCallback(2));
// etc
It's also not hard to make a generic latch-producing function so you can just write stuff like:
var l = makeLatch(callback);
$.get("/a", l());
$.get("/b", l());
$.get("/c", l());
- Stal3r 13y agoYes, you can reinvent wheels and avoid javascript best practices, and lose all benefits of async code control.
- Groxx 13y agoLatches aren't async code control? Javascript has (async) best practices that survive more than a couple years? Promises are great, I totally agree (as long as they're A+ compliant). But they're not on every platform, and it's not (usually) worth building your own if it's not there.
- tmarthal 13y agoA 'count-down latch' is commonly (at least when I learned it, using pthreads) called a 'Conditional Variable'. In your case case, your mutex would be the num_results variable and the conditional is that it is greater than 0.
- rybosome 13y agoTrue, and this would work, but why would you favor this over Promises? They're an open, well-known spec with a lot of implementations - hell, some browsers support them natively. Promises also offer better control over sequential action and error handling.