【问题标题】:How to upload files to s3 synchronously using node.js api如何使用node.js api将文件同步上传到s3
【发布时间】:2016-04-22 18:05:06
【问题描述】:

我有以下代码:

array.forEach(function (item) {

       // *** some processing on each item ***

        var params = {Key: item.id, Body: item.body};
        s3bucket.upload(params, function(err, data) {
            if (err) {
              console.log("Error uploading data. ", err);
            } else {
              console.log("Success uploading data");
        }});
  });

因为 s3bucket.upload 是异步执行的 - 循环在上传所有项目之前完成。

如何强制 s3bucket.upload 同步?

意思是在此项目上传(或失败)到 S3 之前不要跳转到下一个迭代。

谢谢

【问题讨论】:

  • 你不能那样做。相反,请使用承诺。

标签: node.js amazon-s3 aws-sdk


【解决方案1】:

您可以传递一个回发函数,这样剩下的代码只有在上传完成后才会执行。这不能回答您的问题,但可能是另一种选择:

array.forEach(function (item) {

   // *** some processing on each item ***

    var params = {Key: item.id, Body: item.body};
    var f1=function(){
       // stuff to do when upload is ok!
     }
      var f2=function(){
       // stuff to do when upload fails
     }
    s3bucket.upload(params, function(err, data) {

        if (err) {
         f2();
          console.log("Error uploading data. ", err);
         // run my function

        } else {
       // run my function
          f1();
          console.log("Success uploading data");
    }});

  });

【讨论】:

    【解决方案2】:

    最好按照其中一个 cmets 中的建议使用 Promise:

    const uploadToS3 = async (items) => {
      for (const item of array) {
        const params = { Key: item.id, Body: item.body };
        try {
          const data = await s3bucket.upload(params).promise();
          console.log("Success uploading data");
        } catch (err) {
          console.log("Error uploading data. ", err);
        }
      }
    }
    

    【讨论】:

      【解决方案3】:

      你可以使用https://github.com/caolan/async#eacheacheachSeries

      function upload(array, next) {
          async.eachSeries(array, function(item, cb) {
              var params = {Key: item.id, Body: item.body};
              s3bucket.upload(params, function(err, data) {
                  if (err) {
                    console.log("Error uploading data. ", err);
                    cb(err)
                  } else {
                    console.log("Success uploading data");
                    cb()
                  }
              })
          }, function(err) {
              if (err) console.log('one of the uploads failed')
              else console.log('all files uploaded')
              next(err)
          })
      }
      

      【讨论】:

      • 如果没有 asyc 库,我不知道该怎么办。可能在房间的角落里哭了。
      猜你喜欢
      • 2019-12-16
      • 2016-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-25
      • 2021-05-11
      • 2010-10-14
      • 2020-04-05
      相关资源
      最近更新 更多