我有一个foo发出Ajax请求的函数.我怎样才能从中回复foo?
我尝试从success回调中返回值,并将响应分配给函数内部的局部变量并返回该变量,但这些方法都没有实际返回响应.
function foo() {
var result;
$.ajax({
url: '...',
success: function(response) {
result = response;
// return response; // <- I tried that one as well
}
});
return result;
}
var result = foo(); // It always ends up being `undefined`.
Run Code Online (Sandbox Code Playgroud) 例如,我发现了一些基于 promise 的 api 库,我需要在某个时间间隔内使用该库发出 api 请求,无限次(如通常的后端循环)。这个 api 请求 - 实际上是承诺链。
所以,如果我写这样的函数:
function r(){
return api
.call(api.anotherCall)
.then(api.anotherCall)
.then(api.anotherCall)
...
.then(r)
}
Run Code Online (Sandbox Code Playgroud)
会导致堆栈溢出吗?
我想出的解决方案是使用 setTimeout 进行r递归调用。
function r(){
return api
.call(api.anotherCall)
.then(api.anotherCall)
.then(api.anotherCall)
.then(()=>{setTimeout(r, 0)})
}
Run Code Online (Sandbox Code Playgroud)
所以 setTimeoutr只会在调用栈为空时才会调用。
这是好的解决方案,还是有一些递归调用承诺的标准方法?