0

I have ajax nested in the loop. Now I want to merge the ajax returned into an array or a single object. Thanks!

$.each(res.data, function (key, value) {
    SerialNumber = value['serial'];
    Code = value['code_history'][0]['gift_code'];
    return new Promise((resolve, reject)=>{
        $.ajax({
            type: "POST",
            data: "Code=" + Code + "&action=cameraInfo_more" + "&SerialNumber=" + SerialNumber,
            url: "ajax/get-customer-info-params",
            cache: false,
            dataType: "json",
            success: function (res_more) {
                temp2 = res_more.data[0];

                //-- i want merge all json res_more to 1 array

                }
           })
        })
    })
}
LOLWTFasdasd asdad
  • 2,625
  • 5
  • 26
  • 39
  • Have you try with concat? . Before each loop declare empty array . let temp2 = [] and in success function . temp2.concat(res_more.data[0]); – Zar Ni Ko Ko Aug 26 '20 at 05:02
  • You can push your ajax call in array and then use promise.all, to resolve it. Can you please refer answers in this https://stackoverflow.com/questions/38738614/when-all-ajax-requests-complete – bron10 Aug 26 '20 at 05:02

1 Answers1

1

You're using $.each, but if you used Array.prototype.map you would end up with an array of promises. Feed that to Promise.all and wait for it to return.

Here's an example:

Promise.all(res.data.map(value => {
    SerialNumber = value['serial'];
    Code = value['code_history'][0]['gift_code'];
    return new Promise((resolve, reject)=>{
        $.ajax({
            type: "POST",
            data: "Code=" + Code + "&action=cameraInfo_more" + "&SerialNumber=" + SerialNumber,
            url: "ajax/get-customer-info-params",
            cache: false,
            dataType: "json",
            success: function (res_more) {
                resolve(res_more.data[0]);

            }
        })
    })
})).then(x => {
    console.log(x);
});
Daan Meijer
  • 1,324
  • 7
  • 12