所以下面是我的 API 代碼,它接收兩個影像檔案,一個只包含一個影像,另一個包含 5 個影像。然后我正在使用一個名為 cloudinary 的托管網站來上傳它們并接收一個結果,其中包括上傳影像的 URL。我正在嘗試將這些結果推送到 urlArray 中,以便稍后我可以將它們保存到資料庫中。但是,資料庫的代碼在其他所有內容之前執行。當我在最后記錄 urlArray 時也是如此。它只是一個空陣列。我想知道我在這里做錯了什么?
const upload = multer({
storage: multer.diskStorage({
destination: "./public/uploads",
filename: (req, file, cb) => cb(null, file.originalname),
}),
});
const apiRouter = nc({
onNoMatch(req, res) {
res.statusCode(405), json({ error: `method ${req.method} not allowed` });
},
});
const arrayOfImages = upload.fields([
{ name: "cardImage", maxCount: 1 },
{ name: "images", maxCount: 5 },
]);
apiRouter.post(arrayOfImages, (req, res) => {
const urlArray = [];
let cardImage = "";
const imagesArray = req.files["images"];
cloudinary.uploader.upload(
req.files["cardImage"][0].path,
{ folder: "cardImages" },
async (err, result) => {
if (err) console.log(err);
cardImage = result.secure_url;
console.log(`this is the first call ${cardImage}`);
fs.unlinkSync(req.files["cardImage"][0].path);
}
);
for (let i = 0; i < imagesArray.length; i ) {
cloudinary.uploader.upload(
imagesArray[i].path,
{ folder: "Images" },
async (err, result) => {
if (err) console.log(err);
urlArray.push(result.secure_url);
fs.unlinkSync(req.files["images"][i].path);
// TODO : need to implement the data save to database
}
);
}
dataBaseConnection();
const userItem = new Item({
shortDescription: req.body.shortDescription,
longDescription: req.body.longDescription,
price: req.body.itemPrice,
cardImage: cardImage,
images: urlArray,
});
userItem.save((err) => {
if (err) console.log(err);
return console.log("your prodcut has been added to database.");
});
console.log(urlArray);
console.log(`this is the second call ${cardImage}`);
res.redirect("/dashboard");
});
export default apiRouter;
export const config = {
api: {
bodyParser: false, // Disallow body parsing, consume as stream
},
};
uj5u.com熱心網友回復:
我不熟悉 coludinary API 也沒有運行此代碼,但是假設“上傳”回傳一個承諾(看起來確實如此),您可以像這樣等待結果:
注意:您可能需要檢查resultafter await 以確保您立即提取屬性。我對 API 不熟悉。但這是一般的想法。
另請注意,您可能必須將錯誤檢查移到result物件之外。我的示例假設上傳成功
apiRouter.post(arrayOfImages, async(req, res) => { //<< ---- Notice the async
const urlArray = [];
let cardImage = "";
const imagesArray = req.files["images"];
let result = await cloudinary.uploader.upload( //<<-- NOTE: await here
req.files["cardImage"][0].path,
{ folder: "cardImages" },
async (err, result) => {
if (err) console.log(err);
fs.unlinkSync(req.files["cardImage"][0].path);
}
)
cardImage = result.secure_url; //<<-- pull out the value you need from result after await
for (let i = 0; i < imagesArray.length; i ) {
let res = await cloudinary.uploader.upload( //<<-- NOTE: await here
imagesArray[i].path,
{ folder: "Images" },
async (err, result) => {
if (err) console.log(err);
fs.unlinkSync(req.files["images"][i].path);
}
);
urlArray.push(res.secure_url); //<<-- pull out the value you need from result after await
}
dataBaseConnection();
const userItem = new Item({
shortDescription: req.body.shortDescription,
longDescription: req.body.longDescription,
price: req.body.itemPrice,
cardImage: cardImage,
images: urlArray,
});
userItem.save((err) => {
if (err) console.log(err);
return console.log("your prodcut has been added to database.");
});
console.log(urlArray);
console.log(`this is the second call ${cardImage}`);
res.redirect("/dashboard");
});
那么這里發生了什么?
由于該upload函式是異步的,因此您的代碼在第一次上傳和回圈之后都會在“上傳”實際完成之前執行。通過使用await關鍵字,您可以等待承諾回傳。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/513530.html
