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

284
Visualizações
In React how to wait for multiple files to upload before performing further actions?

I am new to Reactjs. I have created an app to upload multiple files to aws s3. I am using a loop to upload all files. I also need to get response from the uploaded file like the filename. This is what I have till now:

const handleClick =  async (event) => {
event.preventDefault();
let newArr = fileInput.current.files;
for (let i = 0; i < newArr.length; i++) {
  const file = newArr[i]
  let newFileName = file.name.replace(/\..+$/, "");
  const ReactS3Client = new S3(config);
  ReactS3Client.uploadFile(file, newFileName).then((data) => {
    if (data.status === 204) {
      console.log( data.key);
    } else {
      console.log("fail");
    }
  });
}

  };

After a lot of googling, I added async to my handleclick. I am super confused. Can anyone please tell me how to wait for the loop to finish? Or just wait for handClick to execute completely? My key also shows undefined if I try to print it out. I can only get response in the .then in handleUpload. But i need to wait for all keys before I can make another api call and change page. Any help is appreciated.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

First thing, you are doing this in the wrong way. ReactS3Client (in your case) should be initialized once.

And about the question you asked. You can use Promise.all().

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

Use it like this.

// Import from other file like config
const ReactS3Client = new S3(config);

const handleClick = async (event) => {
  event.preventDefault();
  try {
    const newArr = fileInput.current.files;
    const v = await Promise.all(
      newArr.map(async (file) => {
        let newFileName = file.name.replace(/\..+$/, "");
        // assuming key is there in response
        const { key } = await ReactS3Client.uploadFile(file, newFileName);
        return {
          newFileName,
          fileKey: key,
        };
      })
    );
    console.log(v);
  } catch (e) {
    console.error(e);
  }
};
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