$ .ajax成功后执行一个函数,而不直接将其放入回调中

Vin*_*ima 2 javascript ajax jquery

我有这个函数,我的代码的很多部分都调用它.

function test() {
  $.ajax({
    url : url,
    type : 'GET',
    success : {
      verifyID();
      verifyName();
      verifyBlah();
    }
  });
}
Run Code Online (Sandbox Code Playgroud)

我还有其他功能:

addProductCart(productID);
Run Code Online (Sandbox Code Playgroud)

在我打电话之前addProductCart(),我需要调用测试功能,但是,其他进程调用测试功能.

我想这样做:

test() ---> if test ok (success) ----> addProductCart()
Run Code Online (Sandbox Code Playgroud)

但我无法将我的函数(addProductCart)设置为成功测试函数,因为,正如我所说,许多其他进程调用测试函数.

我怎样才能做到这一点?

Sha*_*nak 6

使用承诺!

test函数返回一个promise,如下所示:

function test() {
  return $.ajax({ // <----- Notice the return statement here
    url : url,
    type : 'GET',
    success : {
      verifyID();
      verifyName();
      verifyBlah();
    }
  });
}
Run Code Online (Sandbox Code Playgroud)

当您需要使用此函数来测试某些内容并在此过程中执行另一段代码时,您可以执行以下操作:

test().then(function(data, textStatus){
  //do thing 1
  addProductCart()
  // you can use data or textStatus returned by your ajax function here too!
});

test(someParam).then(function(data, textStatus){ // <--- You can even pass parameters to test function like here, and make it do different ajax call based on your param
  //do thing 2
});
Run Code Online (Sandbox Code Playgroud)

有关其工作原理的更多详细信息,请参阅$ .ajaxjQuery文档.功能

这是一个关于JavaScript Promises概念的精彩教程,如果您不熟悉它,可以帮助您入门.