Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 对异步函数进行同步调用_Javascript_Jquery_Ajax - Fatal编程技术网

Javascript 对异步函数进行同步调用

Javascript 对异步函数进行同步调用,javascript,jquery,ajax,Javascript,Jquery,Ajax,假设我有一个异步函数: 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()

假设我有一个异步函数:

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将在内部异步api调用完成之前返回。我知道我可以使用回调来实现这一点,但我正在寻找一种方法来“锁定”异步函数,并仅在得到结果时才恢复。这样我就不必在异步调用之后将所有代码作为回调传递


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

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

我知道你说过你不想使用回调,但除了这样做:

while(foo === undefined){
  sleep(5) //pseudo code sleep method
}
//some code here
$.when(fooAsync()).then(function(results){
    //use the results
});
//some code here after getting back from the async function.
实际上没有任何方法可以锁定当前的执行上下文

另外,对于您提供的代码,该方法将永远不会返回除未定义之外的任何内容。您正在调用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();
}
然后您会将呼叫代码更改为如下所示:

while(foo === undefined){
  sleep(5) //pseudo code sleep method
}
//some code here
$.when(fooAsync()).then(function(results){
    //use the results
});
//some code here after getting back from the async function.

不确定JS,但在C等语言中,在异步函数完成之前,您可以在条件变量上阻塞…我对在JS上实现这一点很感兴趣..您如何调用api,显示一些代码?最简单的解决方案是从同步调用开始。@adeneo-我想让这成为一个一般性问题,这样特定的api与问题无关,您不能在javascript中执行这种阻塞。您可以将请求转换为同步请求,但是这是一个非常糟糕的主意,因为当响应没有及时发生时,它将导致错误的用户体验。更好的处理方法是重新组织代码以异步方式工作。