Cloudinary异步等待一次上传多个图像,然后保存到节点js中的数组

时间:2018-06-24 23:34:35

标签: node.js api cloudinary

嗨,我正在寻找一种使用Node Js asyc等待功能来上传多个图像然后捕获到数组中的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})
}

任何建议将不胜感激。谢谢。

1 个答案:

答案 0 :(得分:1)

在这里我会采取另一种方法。您正在以一种非常难以阅读和调试的方式混淆承诺和异步/等待。

我会这样做: 将文件映射到一个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 */ })
}

以下是带有虚假上传功能和“文件”列表的代码段:

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()