首页 > 解决方案 > 试图等到多个图像上传到 cloudinary

问题描述

我被困在尝试将多个图像上传到 Cloudinary 并在响应中将数组中的 cloudinary url 发回。我一直在想办法在发回 photoAlbum 数组之前等待循环完成,但没有运气。代码看起来像这样:

服务器.js

app.post('/uploadimages', async (req, res) => {
    const { imgFiles, username } = req.body;

    const photoAlbum = await cloudinaryUpload(imgFiles, username)
    
    res.send(photoAlbum)
})

cloudinary.js

require("dotenv").config()
const cloudinary = require("cloudinary").v2


module.exports.cloudinaryUpload = async (imgFiles, username) => {
    const photoAlbum = []

    await imgFiles.forEach((img) => {
        const imageid = uuidv4();

        cloudinary.uploader.upload(
            img,
            {
                folder: username,
                resource_type: "image",
                public_id: imageid,
            }).then((result) => {
                console.log("*** Success: Cloudinary Upload: ", result.url);
                photoAlbum.push({ imageid: imageid, url: result.url });
            }).catch((err) => {
                console.log("*** Error: Cloudinary Upload");
            })
    })

    console.log("Cloudinary upload done: ", photoAlbum);

    return photoAlbum;
}

标签: node.jsexpresscloudinary

解决方案


forEach将始终返回void- 在 JS 中未定义 - 无论回调如何。您想要做的是返回一系列承诺,然后等待它们全部完成。为此,您应该使用map和的组合Promise.all

const promises = imgFiles.map(() => {
  const imageid = uuidv4();

   return cloudinary.uploader.upload(
            img,
            {
                folder: username,
                resource_type: "image",
                public_id: imageid,
            }).then((result) => {
                console.log("*** Success: Cloudinary Upload: ", result.url);
                photoAlbum.push({ imageid: imageid, url: result.url });
            }).catch((err) => {
                console.log("*** Error: Cloudinary Upload");
            });
});

await Promise.all(promises);

map函数创建了一个新的承诺数组,这要归功于 ,return cloudinary.uploader.upload结合Promise.all,await等待所有图像上传。


推荐阅读