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

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

问题描述

我有一个需要2个呼叫到外部服务器来构建其内容和做任何有意义的JavaScript对象。对象是建立这样实例化一个它的实例会自动使这些2调用。 2.调用共享操作返回的数据,然后调用其他方法常见的回调函数。问题是,下一个方法不应该叫,直到两个方法返回。这里是code,因为我现在已经实现了它:

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.

感谢您的任何和所有帮助。

Thanks for any and all help.

推荐答案

有勉强的另一种方式,而不是有这个计数器。另一种选择是使用一个对象{}和添加密钥为每个请求,如果完成了将其删除。这样,你会立刻知道哪些又回来了。但是该解决方案保持不变。

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.

您可以更改code一点点。如果是喜欢你的榜样,你只需要调用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天全站免登陆