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

150
Visualizações
wait for function execution before executing next instruction

I'm trying to upload images to firebase and get the download Url and save the url in the firestore in the database. The code was working until I modified it to handle multiple images. To handle multiple images I have implemented promises.

The functions uploadFiles() and addRecord() works completely fine seperately. But I want to run the functions together in onSubmit() function. The problem I'm facing is that addRecord() runs before the uploadFiles() completes its execution.

I have tried promises and async await to control the flow but unsuccessfull. I'm new to handling promises and stuck at it.

here's the uploadFiles code

const uploadFiles = (data) => {
const promises = [];
data.images.map((file) => {
  console.log("loop");

  const sotrageRef = ref(storage, `files/${file.name}`);

  const uploadTask = uploadBytesResumable(sotrageRef, file);
  promises.push(uploadTask);
  uploadTask.on(
    "state_changed",
    (snapshot) => {
      const prog = Math.round(
        (snapshot.bytesTransferred / snapshot.totalBytes) * 100
      );
      setProgress(prog);
    },
    (error) => console.log(error),
    async () => {
      await getDownloadURL(uploadTask.snapshot.ref).then((downloadURLs) => {
        setUrls((prevState) => [...prevState, downloadURLs]);
        console.log("File available at", downloadURLs);
      });
    }
  );
});
Promise.all(promises)
  .then(() => alert("All images uploaded"))
  .catch((err) => console.log(err));
};

here's the onSubmit function

const onSubmit = async (data) => {
console.log("before upload");
await uploadFiles(data);
console.log("after upload");
console.log(urls);
await addRecord({
  title: data.title,
  eventType: data.eventType,
  date: data.date,
  venue: data.venue,
  description: data.description,
  details: data.details,
  images: urls,
  link: data.link,
  scheduleType: data.scheduleType,
    });
  };

The upload files sets the state of the urls to the image urls from the firebase storage. I have console logged messages before and after the uploadFiles. The console.log(urls) returns an empty array after the uploadFiles is completed, but the values are being populated with urls after the addRecord is being executed. This is resulting the firestore record to be an empty array for images.

Here's a screenshot of the console

enter image description here

Is anything wrong with the way I'm handling promises and async await.

about 4 years ago · Juan Pablo Isaza
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