【问题标题】:AWS SDK S3 calls, inside a forEach while updating the forEach array在更新 forEach 数组时,在 forEach 内调用 AWS SDK S3
【发布时间】:2019-02-23 22:39:59
【问题描述】:

首先我使用 s3.listObject() 方法获取存储桶内的对象列表。这是一个承诺,我将结果发送到另一个函数,我想在其中循环遍历结果并收集每个对象的元数据:

  S3.listObjects({
    Bucket: bucketName,
    MaxKeys: 10,
    Marker: marker,
  })
  .promise()
  .then(collectRedirects)
  .then(callback); // each object in my list should now all have a new property, the metatag

在 collectRedirects 函数中,我需要遍历传入的结果,然后使用另一个异步函数 s3.getObject 来获取元标记。比如:

collectRedirects(objects) {
    objects.forEach(function(e,i,a){
        a[i].foo = S3.getObject({
            Key: e.Key,
            Bucket: bucketName
          })
          .promise()
          .then(function(result){
            Promise.resolve( result.foo );
          });
      }); //end loop
   return objects;
}

但是,循环在 getObject 方法解析之前完成。我的下一步是什么?

我试图将 getObject 方法的结果保存到一个 Promise 数组中,然后运行 ​​Promise.all,但这只是给了我一个未定义值的数组:

var promises = [];
objects.forEach(function(e,i,a){
  let p = S3.getObject({...})
  .promise().then(function(result){ 
    Promise.resolve( result.foo ); 
  });
  promises.push(p);
});
Promise.all(promises)
.then(function(values) {
  console.log(values);
});

我应该怎么做?

【问题讨论】:

  • 不要使用forEach+push,使用map

标签: javascript amazon-s3 promise aws-sdk


【解决方案1】:

你的问题是你不是returning 来自function(result){ Promise.resolve( result.foo ); } 的任何东西。它只是创建一个 Promise,然后丢弃它并返回 undefined

您正在寻找function (result) { return result.foo; }

总之,你会写

collectRedirects(objects) {
  var promises = objects.map(function(e){
    return S3.getObject({
      Key: e.Key,
      Bucket: bucketName
    }).promise().then(function(result){
      return result.foo;
      // or alternatively (if you want to amend the original object)
      e.foo = result.foo;
      return e;
    });
  });
  return Promise.all(promises).then(function(values) {
    console.log(values);
    return values;
  });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-04
    • 1970-01-01
    相关资源
    最近更新 更多