sAn*_*ntd 1 api node.js cloudinary
嗨,我正在寻找一种使用 Node Js asyc 等待功能上传多个图像然后捕获到数组中的 API 服务器端上传解决方案。我按照这个 链接来实现我的代码。在控制台中,它显示了我期望的数组,但它没有给我任何响应。
这是我到目前为止尝试过的,
exports.upload_image = async(req, res) =>{
//let filePaths = req.files.path;
let multipleUpload = new Promise(async (resolve, reject) => {
let upload_len = req.files.length;
let upload_res = new Array();
for(let i = 0; i < upload_len; i++)
{
let filePath = req.files[i].path;
await cloudinary.v2.uploader.upload(filePath, { use_filename: true, unique_filename: false }, function (error, result) {
if(upload_res.length === upload_len)
{
/* resolve promise after upload is complete */
resolve(upload_res)
}
else if(result)
{
/*push public_ids in an array */
upload_res.push(result.public_id);
} else if(error) {
console.log(error)
reject(error)
}
})
}
})
.then((result) => result)
.catch((error) => error)
let upload = await multipleUpload;
res.json({'response':upload})
}
Run Code Online (Sandbox Code Playgroud)
任何建议将不胜感激。谢谢。
我会在这里采取不同的方法。您正在以一种非常难以阅读和调试的方式混淆 promise 和 async/await。
我会这样做:将您的文件映射到一系列承诺,然后调用Promise.all():
exports.upload_image = async(req, res) =>{
// res_promises will be an array of promises
let res_promises = req.files.map(file => new Promise((resolve, reject) => {
cloudinary.v2.uploader.upload(file.path, { use_filename: true, unique_filename: false }, function (error, result) {
if(error) reject(error)
else resolve(result.public_id)
})
})
)
// Promise.all will fire when all promises are resolved
Promise.all(res_promises)
.then(result => res.json({'response':upload}))
.catch((error) => {/* handle error */ })
}
Run Code Online (Sandbox Code Playgroud)
这是一个带有虚假上传功能和“文件”列表的片段:
exports.upload_image = async(req, res) =>{
// res_promises will be an array of promises
let res_promises = req.files.map(file => new Promise((resolve, reject) => {
cloudinary.v2.uploader.upload(file.path, { use_filename: true, unique_filename: false }, function (error, result) {
if(error) reject(error)
else resolve(result.public_id)
})
})
)
// Promise.all will fire when all promises are resolved
Promise.all(res_promises)
.then(result => res.json({'response':upload}))
.catch((error) => {/* handle error */ })
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2399 次 |
| 最近记录: |