我有一个 Javascript 对象,它需要 2 次调用外部服务器来构建其内容并做任何有意义的事情。该对象的构建使得实例化它的实例将自动进行这两个调用。这两个调用共享一个通用的回调函数,该函数对返回的数据进行操作,然后调用另一个方法。问题是在两个方法都返回之前不应该调用下一个方法。这是我目前实现的代码:
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();
}
如您所见,在两个调用都返回后,我强制对象继续使用一个简单的计数器来验证它们都已返回。这可行,但似乎是一个非常糟糕的实现。我现在只使用 Javascript 几个星期,想知道是否有更好的方法来做同样的事情,我还没有偶然发现。
感谢您的任何帮助。