Home > database >  JavaScript fetch inside loop in onSubmit
JavaScript fetch inside loop in onSubmit

Time:10-30

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);    
})

CodePudding user response:

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);    
})
  • Related