Home > other >  map array to ajax request and wait for all to complete
map array to ajax request and wait for all to complete

Time:04-23

I'm trying to run an ajax request on each element of an array. Basically a post request to a php server.

But what is the appropriate way to wait for this result to be completed? What is wrong with the code I wrote below? I need the console.log("step2") to print only after all of the ajax requests are completed.

var results = await Promise.all(
    some_array.map(function(val, key){
        return(
            jQuery.ajax({
                type: 'POST',
                url: '<some/link/to/php/server>',
                dataType: 'json',
                data: val.id,
                xhrFields: {withCredentials: true},
                async: true
            }).done(function(response){         
                run_this_code
            })
        )
    })
)
console.log("step2");

Thanks!

CodePudding user response:

I don't know how jQuery's ajax works, but you can try this:

var results = await Promise.all(
    some_array.map(function(val, key){
            return jQuery.ajax({
                type: 'POST',
                url: '<some/link/to/php/server>',
                dataType: 'json',
                data: val.id,
                xhrFields: {withCredentials: true},
                async: true
            })
    })
)
console.log("step2");

Also I would use fetch or axios since they are more modern. With fetch it would look something like this

const results = await Promise.all(
  some_array.map((val, key) => fetch('<some/link/to/php/server>', {
    method: 'POST',
    credentials: 'include',
    body: JSON.stringify(val.id)
  }).then(res => res.json()))
)

I used modern JavaScript syntax, but you can use the old one as well

CodePudding user response:

You have added console in wrong place first, it should be inside the .done(function(){}). Or you can add new Promise inside the .map function and resolve your promise that will solved your problem.

  • Related