Vinicius Lima
Vinicius Lima

Reputation: 544

Execute a function after $.ajax success without putting it in a callback directly

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.

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.

How can I do this?

Upvotes: 3

Views: 3077

Answers (1)

Shaunak
Shaunak

Reputation: 18018

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

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

Upvotes: 7

Related Questions