等待从javascript函数返回直到满足条件

fin*_*ris 10 javascript closures asynchronous

这是一个奇怪的问题.我有一个客户端对象,我正在使用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;
};
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是我需要加载一些远程JSON资源,然后再返回新的'that'对象(它指示就绪客户端).数据以异步方式返回(显然),我设置布尔变量以指示每个远程资源何时返回.

我想过做以下事情:

return whenInitialized(function() { return that; });
Run Code Online (Sandbox Code Playgroud)

whenInitialized函数返回两个布尔标志是否为真.我将它与setInterval的组合一起使用,但我确信这不起作用.

非常感谢您的建议.

Jor*_*dão 17

为了异步操作成功运行代码,您需要继续.它可以只是代码在操作完成时调用的回调.

像这样的东西:

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;
};
Run Code Online (Sandbox Code Playgroud)

但是这些控制标志真的很烦人,并没有真正扩展.一个更好的,声明性的方法是使用像jQuery deferreds这样的东西:

$.when(jsonRequest1(), jsonRequest2()).then(done);
Run Code Online (Sandbox Code Playgroud)