对async函数进行同步调用

making synchronous call to async function

本文关键字:同步 调用 async 函数      更新时间:2023-12-07

假设我有这个异步函数:

function fooAsync(){
  callSomeApi(some_args, callbackFunction(results){
    return results; //i want to return the results here after the api call.
  }
}

我正在寻找一种方法,将prev函数的返回值分配给var,并且只有当我有这个值时才继续执行代码。

//some code here
var foo = fooAsync();
//some code here after getting back from the async function.

问题是foo将是未定义的,因为javascript将在内部asyncapi调用完成之前返回。我知道我可以使用回调,但我正在寻找一种方法来"锁定"异步函数,只有当它得到结果时才能恢复。这样,我就不必在异步调用后将所有代码作为回调传递。

简而言之,如何以常规同步方式从异步ajax调用(在本例中,我调用googlemapsapi)返回值?

通常,让ajax调用同步是个坏主意。XMLHttpRequest对象上有一个属性,您可以设置它(jQuery允许您轻松地执行此操作)来发出同步ajax请求。我不确定谷歌地图API是否公开了这个功能,但你应该先检查一下。

我知道你说过你不想处理回调,但除了做这样的事情:

while(foo === undefined){
  sleep(5) //pseudo code sleep method
}

确实没有任何方法可以锁定当前的执行上下文。

同样,使用您提供的代码,该方法将永远不会返回除未定义之外的任何内容。您正在调用api方法(异步执行)并立即返回控制。api方法调用的响应处理程序内部的"return"语句只会在匿名函数内部返回。因此,即使能够锁定线程,直到结果返回,您也不会得到它们。

但是,如果您有兴趣以正确的方式进行此操作,那么您应该使用jQuery提供的延迟/承诺模型。

function fooAsync(){
  var deferred = $.Deferred();
  callSomeApi(some_args, callbackFunction(results){
    deferred.resolve(results) //i want to return the results here after the api call.
  }
  return deferred.promise();
}

然后你会把你的呼叫代码改成这样:

//some code here
$.when(fooAsync()).then(function(results){
    //use the results
});
//some code here after getting back from the async function.

jQuery延迟对象文档