我如何將所有結果資料存盤到 pImages 陣列中,我得到了結果,但在這種情況下,我認為異步函式可以作業,但我不知道如何應用它。請幫忙,我的代碼是
exports.addImage = (req, res, next) => {
let imageArray = req.files.productImageArray;
if (!req.files || Object.keys(req.files).length === 0) {
return res.status(400).send("No files were uploaded.");
}
// here all images will be stored in array format
let pImages = [];
for (let f in imageArray) {
imagekit.upload(
{
file: imageArray[f].data, //required
fileName: imageArray[f].name, //required
customMetadata: {
color: req.body.productLabels[f],
default: req.body.defaultProduct[f]
}
},
function(error, result) {
if (error) console.log(error);
else {
console.log(result)
pImages.push(result)
}
}
);
}
console.log("p", pImages); //output p []
};
提前致謝
uj5u.com熱心網友回復:
您可以將 imagekit.upload(...) 包裝在一個承諾中,然后等待這個承諾。
因此,您的承諾必須在 imagekit.upload 的回呼中解決或拒絕。
請注意,您的 addImage 方法現在必須是異步的才能使用 await 關鍵字,因此它本身會回傳一個 Promise。
exports.addImage = async (req, res, next) => {
let imageArray = req.files.productImageArray;
if (!req.files || Object.keys(req.files).length === 0) {
return res.status(400).send("No files were uploaded.");
}
// here all images will be stored in array format
let pImages = [];
for (let f in imageArray) {
try{
const pImage = await new Promise((resolve,reject)=>{
imagekit.upload(
{
file: imageArray[f].data, //required
fileName: imageArray[f].name, //required
customMetadata: {
color: req.body.productLabels[f],
default: req.body.defaultProduct[f]
}
},
function(error, result) {
if (error){
reject(error);
} else {
resolve(result)
}
}
);
});
pImages.push(pImage);
} catch(e){
console.error(e);
}
}
console.log("p", pImages); //output p []
};
您的代碼中還有其他內容我沒有解決。
在第一行中,您正在訪問 req.files.productImageArray 而不檢查 req.files 是否已定義。該檢查是在事后進行的。所以你應該在這個檢查之后移動你的第一行。
req.files.productImageArray 是一個像名字所說的陣列嗎?如果是這樣,您不應該使用 for in 回圈,而是使用 for of 回圈,并且在您的健全性檢查中,您應該包括 Array.isArray(req.files.productImageArray)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/444656.html
標籤:javascript 节点.js 表示 图像套件
上一篇:node.js中pdfkit-tables中的垂直線
下一篇:解決并行保存到mongodb
