How to implement chaining method for ajax in jQuery?

55 Views Asked by At

I have a few Ajax requests which will be executed sequentially.

$.ajax({
  url: 'https://dummyjson.com/products/1',
  success: (res) => {
    console.log(1, res);
    $.ajax({
      url: 'https://dummyjson.com/carts/1',
      success: (res) => {
        console.log(2, res);
        $.ajax({
          url: 'https://dummyjson.com/posts/1',
          success: (res) => {
            console.log(3, res);
            $.ajax({
              url: 'https://dummyjson.com/comments/1',
              success: (res) => {
                console.log(4, res);
              }
            });
          }
        });
      }
    });
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

I know it can be done with new Promise((resolve,reject)=>{}) with async & await function, but I want to use the chaining method for calling AJAX sequentially like this.

ajax1.then((res)=>ajax2).then((res)=>ajax3).then((res)=>ajax4).catch(e => e);

How can implement this with jQuery?

2

There are 2 best solutions below

0
Jordy On BEST ANSWER

I create a custom function called ajax for chaining method implementation.

let ajax = (url, counter) => $.ajax({
  url: url,
  success: (res) => {
    console.log(counter, res);
  }
});

ajax('https://dummyjson.com/products/1', 1).then(() =>
ajax('https://dummyjson.com/carts/1', 2)).then(() =>
ajax('https://dummyjson.com/posts/1', 3)).then(() =>
ajax('https://dummyjson.com/comments/1', 4)).catch((err) =>
console.error(err));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

0
Developer On

Hope this will be helpful.

function ajaxSend(data){
    $.ajax({
      url: data.url,
      context: data.body
    }).done(function(res) {
      return ajaxSend(res);
    }).fail(function() {
    return null;
  })
}

ajaxSend(data);