我正在执行一个函数,将图像从输入文件字段上传到AWS,然后将图像URL和名称保存到mongoDB。我正在使用 NodeJS 和 MongoDB。这是我的例子:
uploadFile(req, res, next) {
let files = req.files;
let images = [];
files.file.forEach((file) => {
uploadToAWS(file.path, {}, function(err, img) {
if (err) { throw err; }
// add path and name to images array
images.push({
path: img[0].url,
name: img[0].name,
});
});
});
// Here the promises should resolve and save to MongoDB the array images
},
无需在每次循环迭代元素时都保存到数据库,我只需填充一个数组images
,然后将其保存到数据库。
最佳答案
为此,您需要使用 Array#map()而不是Array#forEach 。这是因为您打算根据每个值将一些值映射到 promise 。
return Promise.all(files.map((file) => {
// do some stuff with each file here
}));
完整的示例如下所示:
uploadFile(req, res, next) {
let files = req.files;
let images = [];
const promises = files.file.map((file) => {
return uploadToAWS(file.path, {}).then((img) => {
// add path and name to images array
images.push({
path: img[0].url,
name: img[0].name,
});
});
});
// Here the promises should resolve and save to MongoDB the array images
Promise.all(promises).then(next);
}
请注意,在这里,我假设 uploadToAws()
能够返回一个 promise ,因为这是完成这项工作所必需的,否则 cards promise 的房子就会崩溃。如果 uploadToAws()
没有对 Promise 的内置支持,您可以使用 promisify 实用程序,例如 pify使用适配器包装该函数,该适配器将根据回调的结果为您创建一个 promise 。
资源
关于node.js - 如何将 forEach 与 Promises.all 结合起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44175509/