skip to Main Content

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

Answers


  1. Chosen as 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>


  2. 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);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search