在$之后执行一个函数。ajax在没有直接将其放入回调的情况下获得成功

时间:2021-08-28 04:07:23

I have this function where many parts of my code call it.

我有一个函数,我的代码有很多部分调用它。

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

and I have this other function:

还有另一个函数

addProductCart(productID);

Before I call addProductCart(), I need to call test function, but, other processes call test function.

在调用addProductCart()之前,我需要调用test function,但是,其他进程调用test function。

I'd like to do this:

我想这样做:

test() ---> if test ok (success) ----> addProductCart()

But I can't set my function (addProductCart) into success test function because, like I said, many other processes call test function.

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

How can I do this?

我该怎么做呢?

1 个解决方案

#1


6  

Use Promises!

使用承诺!

Return a promise from the test function like so:

从测试函数中返回一个承诺,如下所示:

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

When you need to use this function to test something and execute another piece of code when this passes you can do :

当您需要使用此函数来测试某样东西并在它通过时执行另一段代码时,您可以这样做:

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
});

For more details on how this works see the jQuery docs for $.ajax. function

有关该如何工作的详细信息,请参阅$.ajax的jQuery文档。函数

Here's a great tutorial on concept of JavaScript Promises to get you started if you are unfamiliar with them.

这里有一个关于JavaScript概念的很棒的教程,如果您不熟悉它,可以开始学习它。

#1


6  

Use Promises!

使用承诺!

Return a promise from the test function like so:

从测试函数中返回一个承诺,如下所示:

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

When you need to use this function to test something and execute another piece of code when this passes you can do :

当您需要使用此函数来测试某样东西并在它通过时执行另一段代码时,您可以这样做:

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
});

For more details on how this works see the jQuery docs for $.ajax. function

有关该如何工作的详细信息,请参阅$.ajax的jQuery文档。函数

Here's a great tutorial on concept of JavaScript Promises to get you started if you are unfamiliar with them.

这里有一个关于JavaScript概念的很棒的教程,如果您不熟悉它,可以开始学习它。