连续调用多个函数

call multiple functions successively

本文关键字:函数 调用 连续      更新时间:2023-09-26

我知道这个问题已经被问了好几次了,但是我似乎无法获得使用我的代码的解决方案:等到一个带有动画的函数完成,直到运行另一个函数,jquery等待多个完整事件,等待两个异步函数结束,然后再触发第三个(jQuery延迟?

基本上,我想依次调用四个函数:

#1
function getJason() {
 $.getJSON(rgUrl1,function(json1){
   rgJson1 = json1; ...etc.
 });      

#2
function combineJason() {
  //code to combine 
});

#3
function divideArray() {
  //code to divide stuff 
});

#4
function doOtherStuff() {
  //code to do some other stuff
});
我需要 #1 在调用 #2 之前完成,#2 在 #3 之前完成

,#3 在 #4 之前完成。 过去的帖子让我相信我应该使用延期和承诺。 我已经通读了文档 http://api.jquery.com/category/deferred-object/并尝试了示例但没有成功:

function testing() {
 var deferredObj = $.Deferred();
 var test = getJson()
 var function1 = function () {
  test.done(function(){
    deferredObj.resolve();
    return deferredObj;
   });
  }
  deferredObj.done(function(){
   combineJson();
 });
}; 

此外,大多数示例处理两个函数,而我需要调用几个函数。 我还注意到一些响应包含"setTimeout"。 我有点怀疑,也许是不必要的,使用任何带有计时器、暂停或延迟的东西。 那我就不必猜测该功能需要多长时间吗? 如果一个用户的计算机/连接速度较慢或其他原因怎么办?

jQuery的ajax函数已经返回了一个承诺。因此,如果您使用的是jquery的ajax函数,则不需要创建新的延迟对象。

若要连续调用函数:调用 .then 方法以获取需要调用的函数数。如果一个或多个函数需要执行一些异步任务,则只需返回一个 promise,延迟对象将等待调用下一个then回调,直到返回的承诺解析。每个then回调都将传递前then返回的数据(或者在返回的情况下承诺解析的数据(

$.getJSON(rgUrl1,function(json1){
   rgJson1 = json1; ...etc.
}).then(combineJason)
.then(divideArray)
.then(doOtherStuff);      
//#2
function combineJason(someData) {
  //code to combine 
  return $.getJSON("url to some other json endpoint");
}
//#3
function divideArray(someData) {
  //code to divide stuff 
  //this function is sync so just return some data
  return someNewData;
}
//#4
function doOtherStuff(someData) {
  //code to do some other stuff
  //this function is async so return a promise;
  return $.getJSON("url to some other json endpoint");
}

JSFiddle Demostrating 混合异步/同步继承

连续调用它们非常容易,您不需要等待多个异步事物,而只需等待前一个异步事物。

你会做的

function getJason() {
    return $.getJSON(rgUrl1);
}
function combineJason(json1) {
    //code to combine 
}
function divideArray() {
    //code to divide stuff 
}
function doOtherStuff() {
    //code to do some other stuff
}
getJason().then(combineJason).then(divideArray).then(doOtherStuff);

这将非常类似于

doOtherStuff(divideArray(combineJason(getJason())));

只是如果一个结果是异步的(在这里,$.getJSON getJason 中(,它才需要注意延迟计算(作为回调(。