我在路由中創建了一個函式,它將所有影像上傳到 Cloudinary 3rd 方庫,它將回傳所有 URL 鏈接,我將所有鏈接推送到我的 URL 變數中,然后鏈接將存盤到資料庫中。
我希望在我的 URLs 變數上的鏈接可用之前,它不會插入到我的資料庫中。我對如何使用 async/await 或使用 Promise 感到困惑
這是我的功能路線。我正在使用 node、express、multer。
app.post('/addProduct', async (req, res, next) => {
let urls = [];
async function sendImagesToCloudinary() {
for (let file of req.files) {
await cloudinary.uploader.upload(
file.path,
{
public_id: `${Date.now()}`,
resource_type: 'auto'
}
).then(result => {
//del files after upload on cloudinary
fs.unlink(file.path, function (err) {
if (err) {
console.log(err);
}
});
urls.push(result.url);
})
.catch(err => {
console.log(err);
});
}
res.json(urls);
}
sendImagesToCloudinary();
// Publish on database
const result = await unityMartMediaCollection.insertOne({ urls: urls })
res.json(result)
});
uj5u.com熱心網友回復:
值得 (a) 將各種異步操作分解為更小、更清晰、可測驗的函式,以及 (b) 僅使用一種風格的 promise 語法......
// isolated version of he OP upload
async function upload(file) {
const params = { public_id: `${Date.now()}`, resource_type: 'auto' }
return cloudinary.uploader.upload(file.path, params);
}
// this promisify's fs.unlink (probably natively available in fs.promise)
async unlink(file) {
return new Promise((resolve, reject) => {
fs.unlink(file.path, error => error? reject(error) : resolve());
});
}
// upload, then unlink if upload succeeds, return the url upload result
// catch errors here, so other concurrent uploads can continue
async uploadAndUnlink(file) {
try {
const url = await upload(file);
await unlink(file);
return url
} catch (err) {
console.log(err);
}
}
// implement the route, process the files concurrently
app.post('/addProduct', async (req, res, next) => {
const promises = req.files.map(file => uploadAndUnlink(file));
const urls = await Promise.all(promises);
const result = await unityMartMediaCollection.insertOne({ urls: urls })
res.json(result);
});
我冒昧地洗掉了 URL 生成方法中 res 上的 .json 呼叫。其余代碼的強烈暗示是目的是回傳(給客戶端)unityMartMediaCollection呼叫的結果。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/428873.html
標籤:javascript 节点.js 表示 异步等待 es6-承诺
上一篇:為什么我在操作cv2.error:(-215:Assertionfailed)!src.empty()infunction'cvtColor'之后和小時內收到以下錯誤
下一篇:Express.JS中的這行代碼是什么意思:!user&&res.status(401).json("Wrongcredentials!");它產生的錯誤是什么意思?[復制]
