javascriptjqueryajaxes6-promisejquery-deferred

Call multiple ajax and take only success result using jquery


  1. I have 1 html (2cols, 6rows) and 12 ajaxs.
  2. Each ajax's result will be binding to its own (regardless of success or failure).
  3. Ajax will return 200 or 403. don't know at this time.
  4. ※IMPORTANT※ All result must have to show one same time.
let a1 = $.ajax(1);
let a2 = $.ajax(2);
...
let a12 = $.ajax(12);

I tried

$.when(a1, a2, ... a12).done().fail()
$.when(a1, a2, ... a12).then(done, fail)

All ajax returned 200 → .done() If even one ajax returned 403 → .fail()

So I cannot use $.when()

I don't want to use ajax chain.

$.ajax()
 .complete(() => {
   $.ajax()
    .complete(() => {
      $.ajax()
       .complete(() => {
       })
    })
 })

How can I detected all ajax completed? and How can I gather only succeed result without failed result?


Solution

  • What you're after is Promise.allSettled() which resolves once all the promises passed have completed (resolved or rejected)

    const promises = [a1, a2, ..., a12];
    
    Promise.allSettled(promises).then((results) => {
      const successfulResults = results.reduce((arr, { status, value }, index) => {
        if (status === "fulfilled") {
          arr.push({ index, value }); // in case you need the index
        }
        return arr;
      }, []);
    
      /* looks like
      [
        {
          index: 0,
          value: responseFromA1
        },
        {
          index: 1,
          value: responseFromA2
        },
        ...
      ]
      */
    });