You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何确保所有Cloudinary图片上传完成后再执行MongoDB房产数据创建操作

How to Wait for All Cloudinary Uploads to Complete Before Creating a MongoDB Document in Node.js?

Hey there! That setTimeout workaround is definitely a brittle fix—totally get why it’s failing randomly. The core issue here is that your current code doesn’t properly wait for all the Cloudinary upload promises to resolve before creating the product. Let’s fix this the right way with Promise.all(), which is built exactly for handling batches of asynchronous operations.

Why Your Current Code Fails

  • When you use async inside map, it generates an array of promises—but you’re not actually waiting for any of them to finish.
  • The setTimeout is just guessing when uploads might complete. If uploads take longer than 50 seconds (or even just variable time), your code will try to create the product with an incomplete images array.

The Fix: Use Promise.all()

Here’s how to adjust your code to ensure all uploads finish before creating the product:

Router.post("/createproduct", async (req, res) => { 
  const { error } = productValidation.validate(req.body); 
  if (error) { 
    return res.status(400).json({ message: error.details[0].message }); 
  } 
  try { 
    // 1. Create an array of upload promises (no need to wrap in extra Promise!)
    const uploadPromises = [...req.body.image].map(img => 
      cloudinary.uploader.upload(img, { upload_preset: "fanakaplatinums" })
    );

    // 2. Wait for ALL uploads to resolve (or reject)
    const images = await Promise.all(uploadPromises);

    // 3. Now safely create the product with the full images array
    await productsModel.create({ 
      name: req.body.name, 
      location: req.body.location, 
      description: req.body.description, 
      price: req.body.price, 
      amenities: req.body.amenities, 
      image: images, 
    }); 

    console.log("house created successfully"); 
    res.status(200).json({ message: "house created successfully" }); 
  } catch (error) { 
    // Handle any error (validation, upload failure, or DB creation issue)
    res.status(500).json({ message: error.message }); 
  } 
});

Key Improvements

  • No More Guessing: Promise.all() waits until every upload promise resolves, so you know images is complete before moving on.
  • Cleaner Error Handling: If any upload fails, Promise.all() will throw an error immediately, which gets caught in your outer catch block. This avoids sending multiple conflicting responses (a common issue with your original .catch() inside the map).
  • Simpler Code: You don’t need to manually push to the images array—Promise.all() returns the array of responses directly, in the same order as your original images.

内容的提问来源于stack exchange,提问作者MAXWEL OCHIENG

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 20:17:41