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 之前不要跳转到下一次迭代。
谢谢
您可以使用https://github.com/caolan/async#each each或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)
})
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5085 次 |
| 最近记录: |