我在 s3.upload 的回呼函式中獲取資料,但我想在回圈之外獲取資料。每當我列印 ImageArray 時,它都會列印空,然后列印來自 AWS 的值,但會延遲。來自 AWS 的資料來得并不快。這需要時間。但我想等待所有資料到來,然后繼續其余代碼。我想將它存盤在回圈外的陣列中。怎么做?
app.post("/api/readingsources/new", upload.array("image", 10),
async(req, res) => {
let ImageArray = [];
for (let index in Images) {
const s3 = new AWS.S3({ apiVersion: "2006-03-01" });
const temp = s3.upload({
ACL: "public-read",
Bucket: keys.S3ImageBucket,
Key: `${readingGradeLevel}/${sourceName}-${Date.now()}.${
Images[index].mimetype.split("/")[1]
}`,
Body: Images[index].buffer,
ContentType: Images[index].mimetype,
ServerSideEncryption: "AES256",
},
async(err, data) => {
if (err)
return res.status(500).send(`Server error: ${err.message}`);
const location = await data.Location;
console.log(data.Location);
ImageArray.push(data.Location);
}
);
}
console.log(ImageArray);
}
);
uj5u.com熱心網友回復:
我認為最簡單的方法是承諾回應s3.upload并將承諾存盤在陣列中。然后,在 for 回圈之外,您等待所有結果(這允許并行執行,而在 for 回圈內等待強制順序操作)。
這就是它的樣子:
async (req, res) {
let ImageArray = [];
let promises = [];
for (let index in Images) {
const s3 = new AWS.S3({ apiVersion: '2006-03-01' });
promises.push(
new Promise((resolve, reject) => {
s3.upload(
{
ACL: 'public-read',
Bucket: keys.S3ImageBucket,
Key: `${readingGradeLevel}/${sourceName}-${Date.now()}.${
Images[index].mimetype.split('/')[1]
}`,
Body: Images[index].buffer,
ContentType: Images[index].mimetype,
ServerSideEncryption: 'AES256',
},
(err, data) => {
if (err) {
reject(err);
} else {
resolve(data.Location);
}
}
);
})
);
}
ImageArray = await Promise.allSettled(promises);
console.log(ImageArray);
}
請注意,您必須決定在出現錯誤時要執行的操作。Promise.allSettled將回傳一個包含所有承諾的陣列,但如果您的某些上傳作業正常,您可能不想拋出 500 錯誤......這取決于您來處理這種情況。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/452634.html
