Javascript - 异步调用后同步 [英] Javascript - synchronizing after asynchronous calls

查看:197
本文介绍了Javascript - 异步调用后同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Javascript对象,需要2调用外部服务器来构建其内容,并做任何有意义的事情。该对象被构建为使得实例化它的实例将自动地进行这两个调用。 2个调用共享一个公用的回调函数,它对返回的数据进行操作,然后调用另一个方法。问题是,下一个方法不应该被调用,直到两个方法都返回。这是我目前实现的代码:

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();
}

正如你所看到的,我强制对象继续,返回使用一个简单的计数器来验证他们都已经返回。这工作,但似乎是一个非常差的实施。我现在只用Javascript工作了几个星期,我想知道是否有一个更好的方法做同样的事情,我还没有绊倒。

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.

感谢您提供任何帮助。

推荐答案

另一种方式比拥有这个柜台。另一个选项是使用一个对象{},并为每个请求添加一个键,如果完成,删除它。这样,你会立即知道哪个已经返回。但是解决方案保持不变。

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.

您可以更改代码一点。如果在你的例子中,你只需要调用commonCallback(我称之为otherFunction)里面的另一个函数比你不需要commonCallback。为了保存上下文,你已经使用闭包。而不是

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);
            });

您可以这样做

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

这篇关于Javascript - 异步调用后同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆