我尝试使用nodejs lambda函数将图像上传到aws s3存储桶。但对于初始调用,没有文件被上传,并且当下次尝试时,先前的文件被上传。
即使我们在异步等待中使用,它也不能同步工作。
async uploadAttachment(attachment, id) {
try {
let res = '';
attachment.forEach(async (element, index) => {
const encodedImage = element.base64;
const fileTypeInfo = element.fileextType;
const fileName = `${Math.floor(new Date() / 1000)}_${index + 1}.${fileTypeInfo}`;
const decodedImage = Buffer.from(encodedImage, 'base64');
const filePath = `${id}/${fileName}`;
const params = {
Body: decodedImage,
Bucket: process.env.S3_FRF_BUCKET,
Key: filePath
};
res = await s3.upload(params, () => {});
});
return res;
} catch (e) {
throw e;
}
}
有什么建议吗?
常规数组上的
.forEach
不能像人们期望的那样与 async/await 一起使用。使用 for..of
代替。
for(let element of attachment) {
// await actually waits here
}
我是一名优秀的程序员,十分优秀!