如何使用Node.js API同步地将文件上传到S3

5

我有如下的代码:

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之前不要跳到下一个迭代。

谢谢。


你不能这样做。相反,使用 promises。 - SLaks
3个回答

4
你可以使用https://github.com/caolan/async#eacheach或者eachSeries
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)
    })
}

1
没有异步库,我不知道该怎么办。可能会在房间的角落里哭泣。 - Julian

3
最好按照其中一个评论建议的方式使用 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);
    }
  }
}

2

你可以传递一个回调函数,这样只有当上传完成后,剩下的代码才会执行。这并不是回答你的问题,但可能是另一个可选项:

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");
    }});

  });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接