Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

125
Vistas
React function await not working. Executing at the same time

I am uploading products into database. I have a submit function:

 const onSubmit = async (e) => {
    e.preventDefault()

    try {
      await uploadImage()
 
      //this executes at the same time as the above function
      window.location.reload()

    } catch (error) {
      alert(error)
    }
  }

Everything under uploadImage doesn't wait for it to finish

this uploadImage function takes the image and uploads it to cloudinary like this:

  const uploadImage = async () => {
    const data = new FormData()
    if (formImage) {
      data.append("file", formImage)
      data.append("upload_preset", "***-")
      data.append("cloud_name", "***")
      try {
        const resp = await fetch("***", {
          method: "post",
          body: data
        })
        const dataJson = await resp.json()
        setUrl(dataJson.secure_url);

//I  had insertProduct Function under the other one on submit but they executed at the same time so it didn't work

        insertProduct(producto, dataJson.secure_url)
      } catch(error) {
        console.log(error)
      }
    }
  }

I have these two functions inside the same file.

↓↓↓↓ This is my inserProduct function ↓↓↓↓

Now this insertProduct function I have it in a .js file outside /pages

import { collection, query, where, addDoc, getDoc, getDocs } from "firebase/firestore";
import { db } from "../config/firebase";

export const insertProduct = async (prodData, image) => {
  const {
    nombre, precioOferta, precioRegular,
    cantStock, sku,
    breveDescripcion, visible,
    envioGratis, coincideMedidas,
    descripcion, picture,
    etiquetas, vendor,
    available_colors, available_sizes
  } = prodData

  const tags = etiquetas.split(" ")
  if (image) {
    try {
      const uploadedProduct = await addDoc(collection(db, "products"), {
        name: nombre,
        price: precioOferta,
        regular_price: precioRegular,
        vendor: {
          vendor_id: vendor.vendor_id
        },
        sku,
        freeShipping: envioGratis,
        stock_quantity: cantStock,
        is_published: visible,
        short_description: breveDescripcion,
        description: descripcion,
        picture: image,
        tags,
        available_sizes,
        available_colors
      })
      return uploadedProduct
    } catch (error) {
      console.log(error)
    }
  }else{
    console.log('no hay imagen')
  }
}

And this is what this function does.

My problem is with the onSubmit function which the code under the function is inmediately executing when the above function is called.

I hope you can help me! Thanks in advance.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Try to make a use of Promise.all() as it's described in docs. Smth like this

await Promise.all(
      await uploadImage()
      await window.location.reload()
    )
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda