Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

144
Views
Wait for async forEach that in a callback function to finished then return data

I'm a newbie in asynchronous javascript. I want to use an async forEach with Promise Array method but In javascript await is only valid for the async function but we can not mark a callback function as an async. I know I make a logical mistake. How can achieve that? Any Help?

Also you can give me an advise about that if-else hell. How can I avoid that if-else hell.

My try with Promise Array:

router.get("/", async (req, res) => {
  const token = req.cookies.jwt;
  let cartObjects = [];
  cartRequests.getCart( token, (cartError, cartData) => {
    if (cartError) {
      return res.status(400).render('error', {message: cartError})
    }    

    if(cartData.error)
    {
      if (cartData.error==="There is no cart created for this user") {
        return res.status(200).render("cart/cartPage", { cartObjects });
      }
      else if(cartData.error === "Invalid Token"){
        return res.status(200).render('error', {message: 'Not authenticated.'})
      } else{
        return res.status(400).render('error', {message: cartData.error})
      }
      
    }

    const cartItems = cartData.items;
    let cartItemIndex = 0;
    let promises = []

    cartItems.forEach(async (item) => {
      let productId = item.productId;
       promises.push( new Promise((resolve, reject) => {
        productRequets.getProductById(productId, (productErr, productData) => {
          if (productData.error) {
            reject(productData.error);
          } else {
            let cartObject = getCartObject(
              productData,
              cartItems,
              cartItemIndex
            );
            resolve(cartObject);
          }
        });
      }))
        .catch((err) => {
          
        })
        .then((resolvedData) => {
          cartObjects.push(resolvedData);
        });
    });
    
    await Promise.all(promises)
    return res.status(200).render("cart/cartPage", { cartObjects });
  });
});
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!