Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

315
Visualizações
How to wait fetch api to finish using async/await?

I have this Javascript program that will load images from my local server to datatransfer, then assign its files to my input with type file, but I really don't have an idea on how to wait for the fetch API to finish before executing the later part of the program. I'm hoping you can help me with my problem because I'm a beginner.       

function image_select(BHID) {
    all_fileBuffer[BHID] = new DataTransfer();
     //add images from database to filebuffer
    setTimeout(async function () {
    $("div#container-"+BHID+" img").each(async function (e) {
        await fetch($(this).attr('src'))
            .then(res => res.blob())
            .then(blob => {
                all_fileBuffer[BHID].items.add(new File([blob], $(this).attr('id'), blob));
            })
        
    }); 
    }, 1000);

    all_attachments[BHID] = document.getElementById("image-" + BHID).files; // <-- reference your file input here

    // append the file list to an array iteratively
    for (let i = 0; i < all_attachments[BHID].length; i++) {
        // Exclude file in specified index
        all_fileBuffer[BHID].items.add(all_attachments[BHID][i]);
    }
    document.getElementById('image-' + BHID).files = all_fileBuffer[BHID].files;
    all_image[BHID] = document.getElementById('image-' + BHID).files;

    all_images[BHID] = [];
    for (i = 0; i < all_image[BHID].length; i++) {
        all_images[BHID].push({
            "name": all_image[BHID][i].name,
            "url": URL.createObjectURL(all_image[BHID][i]),
            "file": all_image[BHID][i],
        })
    }
    document.getElementById('container-' + BHID).innerHTML = "";
    document.getElementById('container-' + BHID).innerHTML = image_show(BHID);
            

console.log(all_fileBuffer[BHID].files); 
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I don't quite understand what part of code you need to use after your fetch, but multiple async functions are handled like this

async function main () {
  await Promise.all([1, 2, 3].map(x => 
        new Promise((resolve) => 
          setTimeout(resolve, x*1000)))
  )

  console.log('further code')
}

So in your case it would look something like this:

async function imageSelect () {
// ...
    await Promise.all([
        $("div#container-"+BHID+" img").map(async function (e) {
            await fetch($(this).attr('src'))
                .then(res => res.blob())
                .then(blob => all_fileBuffer[BHID].items.add(
                    new File([blob], $(this).attr('id'), blob));
        })
    ]);
    
    console.log('fetch done')
// ...
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda