Sunday, May 19, 2024
123
rated 0 times [  125] [ 2]  / answers: 1 / hits: 19729  / 15 Years ago, wed, may 13, 2009, 12:00:00

I have a Javascript object that requires 2 calls out to an external server to build its contents and do anything meaningful. The object is built such that instantiating an instance of it will automatically make these 2 calls. The 2 calls share a common callback function that operates on the returned data and then calls another method. The problem is that the next method should not be called until both methods return. Here is the code as I have implemented it currently:



foo.bar.Object = function() {
this.currentCallbacks = 0;
this.expectedCallbacks = 2;

this.function1 = function() {
// do stuff
var me = this;
foo.bar.sendRequest(new RequestObject, function(resp) {
me.commonCallback(resp);
});
};

this.function2 = function() {
// do stuff
var me = this;
foo.bar.sendRequest(new RequestObject, function(resp) {
me.commonCallback(resp);
});
};

this.commonCallback = function(resp) {
this.currentCallbacks++;
// do stuff
if (this.currentCallbacks == this.expectedCallbacks) {
// call new method
}
};

this.function1();
this.function2();
}


As you can see, I am forcing the object to continue after both calls have returned using a simple counter to validate they have both returned. This works but seems like a really poor implementation. I have only worked with Javascript for a few weeks now and am wondering if there is a better method for doing the same thing that I have yet to stumble upon.



Thanks for any and all help.


More From » asynchronous

 Answers
68

There is barely another way than to have this counter. Another option would be to use an object {} and add a key for every request and remove it if finished. This way you would know immediately which has returned. But the solution stays the same.



You can change the code a little bit. If it is like in your example that you only need to call another function inside of commonCallback (I called it otherFunction) than you don't need the commonCallback. In order to save the context you did use closures already. Instead of



foo.bar.sendRequest(new RequestObject, function(resp) {
me.commonCallback(resp);
});


you could do it this way



foo.bar.sendRequest(new RequestObject, function(resp) {
--me.expectedCallbacks || me.otherFunction(resp);
});

[#99547] Friday, May 8, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
blaisep

Total Points: 748
Total Questions: 95
Total Answers: 108

Location: Federated States of Micronesia
Member since Sun, May 16, 2021
3 Years ago
blaisep questions
Wed, Dec 16, 20, 00:00, 4 Years ago
Sun, Aug 16, 20, 00:00, 4 Years ago
Tue, Nov 12, 19, 00:00, 5 Years ago
Mon, Nov 11, 19, 00:00, 5 Years ago
;