2

I have been trying to call multiple ajax call in async mode and then waiting for all the ajax calls to complete before proceeding. I am using jquery .when().

var results_array = [];
var num = 0;
var promises = [];

    ldap_cmd_array.forEach(element => {
        var myldap = ldap_data;
        myldap.push({
            "name": "cmd",
            "value": element
        });
        console.log(++num);
        promises.push(ajaxCall(myldap, 'aaa',
            // success callback
            function (data) {
                console.log(--num);
                results_array.push(data);
                console.log('pass');
            },
            //error callback
            function (err) {
                //Do nothing
                console.log(--num);
                console.log('fail');
            }
        ));
    });
    $.when.apply($, promises)
      .then(function() {
        console.log(results_array);
    });

But in the output, I see that results_array is printing before all the ajax call is completed. I'm not sure where I am going wrong. Need help? Thanks in advance.

Note: output image is attached.

Chrome browser console output

user2636593
  • 43
  • 1
  • 3
  • Does `ajaxCall` actually return a promise? If not, that would explain what you are seeing. If it does indeed return a promise, then use `.then`, not success and error callbacks. You are just making it more complicated for yourself than it needs to be. – Felix Kling Jul 13 '18 at 05:20
  • What is `ajaxCall`? (It looks to be using a callback, which isn't a great sign if you're trying to use it as a Promise) – CertainPerformance Jul 13 '18 at 05:20
  • Is ajaxCall is aync()? If not, then make it async. use an await within that call to get it's response before it executes next bit. – bh4r4th Jul 13 '18 at 05:30
  • Could this answer to a simillar problem give you some inputs? https://stackoverflow.com/questions/13912775/jquery-deferred-getting-result-of-chained-ajax-calls/13913059#13913059 – Zim84 Jul 13 '18 at 05:33
  • Possible duplicate of [jQuery.when - Callback for when ALL Deferreds are no longer 'unresolved' (either resolved or rejected)?](https://stackoverflow.com/questions/5824615/jquery-when-callback-for-when-all-deferreds-are-no-longer-unresolved-either) – Tibrogargan Jul 13 '18 at 06:22
  • Any particular reason `$.when(...promises)` won't work? – Tibrogargan Jul 13 '18 at 06:25
  • ajaxCall() is just a wrapper for ajax where I am adding some data before calling $.ajax(). If I am not doing the right way then is there a way to call ajaxCall() method in async way and get its response? – user2636593 Jul 13 '18 at 06:56
  • *"If I am not doing the right way"* How should we know if we don't see the code of `ajaxCall`? – Felix Kling Jul 13 '18 at 16:19

2 Answers2

0

Finally I was able to solve it. Thanks to Zim84, your pointer actually solved my problem, kudos!!

var results_array = [];
var num = 0;

var promises = [];
console.log(ldap_data);
ldap_cmd_array.forEach(element => {
    var myldap = ldap_data.slice(); //to copy a javascript object
    myldap.push({
        "name": "cmd",
        "value": element
    });
    var dObject = new $.Deferred();
    console.log(++num);
    promises.push(dObject);
    ajaxCall(myldap, 'taaa',
        // success callback
        function (data) {
            console.log(--num);
            dObject.resolve();
            results_array.push(data);
            console.log('pass');
        },
        //error callback
        function (err) {
            //Do nothing
            dObject.resolve();
            console.log(--num);
            console.log('fail');
        }
    );
});
$.when.apply($, promises)
    .then(function () {
        console.log('I should print after all promises');
        console.log(results_array);
    });

enter image description here

user2636593
  • 43
  • 1
  • 3
  • Thanks to everyone for spending your valuable time to help me out. You are wonderful people. Thank you !! – user2636593 Jul 13 '18 at 09:18
  • This is unnecessarily complex. `$.ajax` already returns a promise. Use that instead. If `ajaxCall` returned the promise returned by `$.ajax`, then your code could just be `Promise.all(ldap_cmd_array.map(element => { /*... */ return ajaxCall(myldap, 'taaa').catch(() => null); })).then(results_array => console.log(results_array));` No need for creating a deferred object or using callbacks. – Felix Kling Jul 13 '18 at 16:26
-2
Promise.all([ajaxCall1, ..., ajaxCallN]).then(responseArray => {})
MMaks
  • 11
  • 1