如何确保所有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
asyncinsidemap, it generates an array of promises—but you’re not actually waiting for any of them to finish. - The
setTimeoutis 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 incompleteimagesarray.
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 knowimagesis complete before moving on. - Cleaner Error Handling: If any upload fails,
Promise.all()will throw an error immediately, which gets caught in your outercatchblock. 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
imagesarray—Promise.all()returns the array of responses directly, in the same order as your original images.
内容的提问来源于stack exchange,提问作者MAXWEL OCHIENG
相关产品推荐
相关产品推荐

