排序函数调用

Ordering the function calls

我必须按顺序调用函数,但不知何故它们独立工作。

函数如下:

function a(){
  Ajax_Call_1();
}

function b(){
  Ajax_Call_2();
}

function c(){
  Ajax_Call_3();
}

$.when( a() ).then( $.when( b() ).then( c() ) );

当我运行它时,它看起来像:

A works

C works

B works

但有时:

C works

A works

B works

如何订购?

您可以通过返回它们按顺序链接它们:

$.when(a()).then(function() {
    return b();
}).then(function() {
    return c();
}).then(function() {
    console.log("Done!");
});

您可以使用 then 方法链接类似 promise 的对象。注意 thendone/fail 之间的区别,传递给 thendone 回调可以 return 一个新的类似 promise 的对象其余的控制流程。这就是您可以进行链接的原因。参见 the documentation

a().then(b).then(c).done(function() { // the last promise has been resolved });

您的所有函数都应该 return promise 对象才能正常工作。所以你的 b 应该是这样的。

function b(){
  return Ajax_Call_2();
}

其中 Ajax_Call 本身应该 return ajax 调用,例如 return $.ajax(...).

请注意,作为 bc return 的承诺,您可以将它们直接传递给 then