通过JavaScriptjoin主题

大概问过之前,但经过严肃的search,我仍然无法find一个合适的解决scheme。 请考虑这样的事情:

function compute() { asyncCall(args, function(err, result) { }); /* 'join thread here' */ } 

即使asyncCall是asynchronous的,我想使用result并从函数compute同步返回。 asyncCall是一个库调用,我不能以任何方式修改它。

如何在没有setTimeout的情况下正确地等待asynchronous结果并观察条件variables? 这是可能的,但不是最理想的。

浏览器中没有可用的语法。 您的选项通常仅限于callback模式或承诺。

NodeJS遵循大多数asynchronous方法的callback模式。

 function someAsyncMethod(options, callback) { //callback = function(error, data) // when there is an error, it is the first parameter, otherwise use null doSomethingAsync(function(){ callback(null, response); }); } .... someAsyncMethod({...}, function(err, data) { if (err) return alert("OMG! FAilZ!"); // use data }); 

另一个常见的实现是承诺,如jQuery的.ajax()方法…

 var px = $.ajax({...}); px.data(function(data, xhr, status){ //runs when data returns. }); px.fail(function(err,xhr, status){ //runs when an error occurs }); 

承诺类似事件…

在上述两种方法中,callback语法往往容易实现和遵循,但是可以导致深度嵌套的callback树,尽pipe您可以使用实用程序模式,像asynchronous这样的方法来克服这一点。

不知道如何才能真正使用尚不存在的东西,但很容易返回一个插槽,其结果是:

 function compute() { var rez=[]; asyncCall(args, function(err, result) { rez[0]=result; if(rez.onchange){ rez.onchange(result); } }); /* 'join thread here' */ return rez; } 

现在,你可以引用return的[0]属性,一旦callback进来,compute()[0]就会得到结果。 它还会触发一个事件处理程序,您可以附加到返回的数组,当数据在callback中更新时将触发。

我会用更正式的承诺或二次callback,但这就是我…

编辑:如何整合callback上游:

 // sync (old and busted): function render(){ var myView=compute(); mainDiv.innerHTML=myView; } //async using my re-modified compute(): function render(){ var that=compute(); that.onchange=function(e){ mainDiv.innerHTML=e; } } 

看看如何使它只等待渲染函数中添加一个包装?