您好,我正在寻找一种使用 Node Js 异步等待功能来上传多个图像然后捕获到数组中的 API 服务器端上传解决方案。我关注这个link来实现我的代码。在控制台中,它显示了我期望的数组,但它没有给我任何响应。
这是我迄今为止尝试过的,
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})
}
如有任何建议,我们将不胜感激。谢谢。
我会在这里采取不同的方法。您以一种很难阅读和调试的方式混合了 promise 和异步/等待。
我会这样做:将您的文件映射到 Promise 数组,然后调用 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 */ })
}
这是一个带有虚假上传功能和"file"列表的片段:
function upload(file, fn) {
// fake upload file, just return file as id
setTimeout(() => fn(null, {
public_id: file
}), Math.floor(Math.random() * 500))
}
// fake req.files
let files = [1, 2, 3, 4, 5, 6]
let upload_image = () => {
let upload_res = files.map(file => new Promise((resolve, reject) => {
upload(file, (error, result) => {
if (error) reject(error)
else resolve(result.public_id);
})
}))
Promise.all(upload_res)
.then(result => console.log({
'response': result
}))
.catch(error => error)
}
upload_image()
我是一名优秀的程序员,十分优秀!