node.js - 试图等到多个图像上传到 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;
}
解决方案
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
等待所有图像上传。
推荐阅读
- javascript - 如何在 Vue.js 中使用 dom-to-image 或 html2canvas?
- python - 如何绘制均值为 0 的协方差误差椭圆?
- firebase - Firebase - 权限不足,即使我是项目所有者
- visual-studio-code - VS 代码片段 | 占位符 + 变换
- python - 未知?塑造 keras 深度学习
- c# - 需要等待单位获得服务器时间才能开始制作
- excel - 使用宏隐藏行而不破坏公式/函数
- dart - Pusher ChatKit Api 缺少 Https 标头
- c# - Log4Net 停止记录,如何恢复?
- python - Python BeautifulSoup - 从给定的 URL 中使用 iframe 抓取多个网页