我正在使用aws上传用户输入的图像,然后从亚马逊获取图像链接,我将在mongoDB中存储该链接。在这种情况下,当我运行.upload()时,它是异步的。
const imgSRC = [];
for (let img of image) {
console.log(img);
const params = {
Bucket: process.env.AWS_BUCKET,
Key: `${img.originalname}_${userID}`,
Body: img.buffer,
};
s3.upload(params, (error, data) => {
if (error) {
console.log(error);
res.status(500).json({ msg: "server error" });
}
imgSRC.push(data.Location);
console.log(imgSRC);
});}
const newPost = new Post({
userID: userID,
contentID: contentID,
posts: [
{
caption: caption,
data: imgSRC,
},
],});const post =等待newPost.save();
在mongodb .save运行情况下,还没有来自亚马逊网络服务的imgLinks。我怎么才能修好这些东西。
我已经试过异步了,但不起作用
发布于 2020-10-01 14:26:21
您需要以这种方式使用Promise.all()
const uploadImage = (obj) => {
return new Promise((resolve, reject) => {
const params = {
Bucket: process.env.AWS_BUCKET,
Key: obj.key,
Body: obj.body,
}
s3.upload(params, (error, data) => {
if (error) {
console.log(error);
return reject(error);
}
return data;
});
})
}
const mainFunction = async () => {
const promises = [];
for (let img of image) {
const options = {
key: `${img.originalname}_${userID}`,
body: img.buffer
};
promises.push(uploadImage(options));
}
const result = await Promise.all(promises);
const imgSRC = result.map((r) => { return r.Location });
return imgSRC;
}发布于 2020-10-01 14:27:37
如果在s3.upload方法上使用await,则应该删除此方法的回调。
try {
const data = await s3.upload(params);
imgSRC.push(data.Location);
console.log(imgSRC);
} catch(e) {
console.log(error);
res.status(500).json({ msg: "server error" });
}如果它起作用了,请告诉我。
https://stackoverflow.com/questions/64150011
复制相似问题