Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

184
Views
JavaScript fetch inside loop in onSubmit

How I can organize my code that console.log(url) calls after each loop?

$("form").on('submit', (e) => {
    e.preventDefault();
    
    const form = $("form");
    if (!form.checkValidity()) return;
    
    const formData = new FormData(form[0]);

    $(".file-upload-wrapper img.card-img").each(async function (i) {
        
        const src = $(this).attr("src");
        const fileName = $(this).attr("data-filename");

        const response = await fetch(src);
        const data = await response.blob();
        formData.append("file", data, fileName);
        
        console.log(src);   
    })

    const url = $(form).attr("action");
    console.log(url);    
})
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

await works inside for..of loops, not inside synchronous array methods like .forEach() and .map(). I suspect it doesn't work either inside jQuery's $.each(), because only the inner function is async; the outer code remains synchronous, so you are getting your last console.log(url) before anything else. Try with a for...of loop instead:

$("form").on('submit', async (e) => { // async here
    e.preventDefault();
    
    const form = $("form");
    if (!form.checkValidity()) return;
    
    const formData = new FormData(form[0]);

    const $images = $(".file-upload-wrapper img.card-img");
    
    for (let image of $images) {
        const $image = $(image);
        const src = $image.attr("src");
        const fileName = $image.attr("data-filename");
    
        const response = await fetch(src);
        const data = await response.blob();
        formData.append("file", data, fileName);
        
        console.log(src);   
    }

    const url = $(form).attr("action");
    console.log(url);    
});
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!