API将文件同步上传到s3

API将文件同步上传到s3

本文介绍了如何使用Node.js API将文件同步上传到s3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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是异步执行的-循环在上载所有项目之前完成.

Because s3bucket.upload is being executed asynchronously - the loop finishes before uploading all the items.

如何强制s3bucket.upload同步?

How can I force s3bucket.upload to be synchronous?

意思是直到将该项目上载(或失败)到S3之前,都不要跳转到下一个迭代.

Meaning don't jump to next iteration until this item was uploaded (or failed) to S3.

谢谢

推荐答案

您可以使用 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)
    })
}

这篇关于如何使用Node.js API将文件同步上传到s3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 13:16