这是一个奇怪的问题。我有一个正在使用 Crockford 式公共/私有成员构建的客户端对象:
var client = function() {
var that, remote_data, other_data;
// add public interface
that.doStuff = function(){...}
// wait for remote resources to load
remote_data = jsonRequest1();
other_data = jsonRequest2();
return that;
};
我遇到的问题是,我需要在返回新的“那个”对象(表示客户端准备就绪)之前加载一些远程 JSON 资源。数据是异步返回的(显然),我设置布尔变量来指示每个远程资源何时返回。
我考虑过做类似以下的事情:
return whenInitialized(function() { return that; });
whenInitialized 函数返回两个布尔标志是否都为 true。我会将其与 setInterval 结合使用,但我确信这行不通。
非常感谢您的建议。
为了运行代码after异步操作已成功,您需要一个延续。它可以只是操作完成时代码调用的回调。
像这样的事情:
var client = function(done) { // done is the callback
var that, remote_data, other_data;
// add public interface
that.doStuff = function(){...}
// wait for remote resources to load
var done1 = false, done2 = false;
var complete1 = function() { done1 = true; if (done2) done(); };
var complete2 = function() { done2 = true; if (done1) done(); };
remote_data = jsonRequest1(complete1);
other_data = jsonRequest2(complete2);
return that;
};
但这些控制标志确实很烦人,而且不能真正扩展。一种更好的、声明性的方法是使用类似的东西jQuery 延迟 http://www.erichynds.com/jquery/using-deferreds-in-jquery/:
$.when(jsonRequest1(), jsonRequest2()).then(done);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)