Search code examples
javascriptjqueryasynchronouses6-promisejquery-deferred

jQuery deferreds - order of execution in multiple blocks


NOTE
This problem somehow happens only with a specific server-side api. Therefore it addresses the wrong problem. I'll not delete it since it have answers and comments.


I'm trying to execute a few ajax requests, do some stuff after each is done and some other stuff after all of them are done, for that I'm using the code below:

let
        myarr = [],
        myfunc = arg => myarr.push(arg);

$.when(
    $.post(myparams).done(myfunc),
    $.post(otherparams).done(myfunc),
    $.post(yetanother).done(myfunc)

// it comes out with only one arg
).then(e => console.log(myarr));

But when it comes to execute the then block it usually has only executed the done of the first operation, how could I fix that?

I'm sorry if it's a duplicate but honestly I didn't even knew what to search for :/


Comment

I also tried to create my own deferreds where I would execute the ajax and resolve them inside the done block, but that yielded the same results.

Using only done or only then, same.


Solution

  • Per jQuery's documentation on $.when():

    Each argument [of .then()] is an array with the following structure: [ data, statusText, jqXHR ]

    Meaning you could do something like this...

    $.when(
      $.post(myparams),
      $.post(otherparams),
      $.post(yetanother)
    ).then((res1, res2, res3) => { //Arg for each result
      myfunc(res1[0]);             //Call myfunc for result 1's data
      myfunc(res2[0]);             //Call myfunc for result 2's data
      myfunc(res3[0]);             //Call myfunc for result 3's data
    });
    

    Though perhaps a cleaner version might be something like this instead...

    let
      myarr = [],
      myfunc = arg => myarr.push(arg);
    
    $.when(
      $.get('https://jsonplaceholder.typicode.com/todos/1'),
      $.get('https://jsonplaceholder.typicode.com/todos/2'),
      $.get('https://jsonplaceholder.typicode.com/todos/3')
    ).then((...results) => {                  //Get all results as an array
      results.map(r=>r[0]).forEach(myfunc);   //Call myfunc for each result's data
      console.log(myarr);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>