如何使用node.js api同步上传文件到s3

bel*_*oky 5 amazon-s3 node.js aws-sdk

我有以下一段代码:

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");
        }});
  });
Run Code Online (Sandbox Code Playgroud)

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

如何强制 s3bucket.upload 同步?

这意味着在此项目上传(或失败)到 S3 之前不要跳转到下一次迭代。

谢谢

Kri*_*vas 4

您可以使用https://github.com/caolan/async#each eacheachSeries

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)
    })
}
Run Code Online (Sandbox Code Playgroud)