• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

151
Views
map array to ajax request and wait for all to complete

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!

about 3 years ago · Santiago Trujillo
1 answers
Answer question

0

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

about 3 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error