等待从javascript函数返回,直到满足条件 [英] Wait to return from a javascript function until condition met

查看:145
本文介绍了等待从javascript函数返回,直到满足条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个奇怪的问题。我有一个客户对象,我正在使用Crockford的公共/私有成员构建:

This is an odd problem. I have a client object that I am building up using Crockford-esque public/private members:

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资源, 'that'对象(它指示一个就绪的客户端)。数据是异步返回的(显然),我设置布尔变量来指示每个远程资源何时返回。

The problem I'm having is that I need to load some remote JSON resources prior to returning the new 'that' object (which signals a ready client). Data is returned asynchronously (obviously), and I am setting boolean variables to indicate when each remote resource has returned.

我想过做一些类似下面的事情: / p>

I've thought about doing something like the following:

return whenInitialized(function() { return that; });

whenInitialized函数返回是否两个布尔标志都为true。我会用setInterval的组合,但我相信这不会工作。

The whenInitialized function returns whether or not both of the boolean flags are true. I'd use this with a combination of setInterval, but I am sure this won't work.

感谢您的建议。

推荐答案

为了在之后运行代码,异步操作成功,您需要一个延续

In order to run code after an asynchronous operation has succeeded, you need a continuation. It can be just a callback that your code calls when the operations are complete.

这样的东西:

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延迟

But these controlling flags are really annoying and don't really scale. A better, declarative way of doing this is using something like jQuery deferreds:

$.when(jsonRequest1(), jsonRequest2()).then(done);

这篇关于等待从javascript函数返回,直到满足条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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