简体   繁体   English

在 Promise 中获取存储桶中的所有 Amazon S3 文件

[英]Get all Amazon S3 files inside a bucket within Promise

I'm trying to grab thousands of files from Amazon S3 within a Promise but I can't seem to figure out how to include the ContinuationToken within if the list is truncated and gather it all together within the promise.我正在尝试从 Promise 中的 Amazon S3 中获取数千个文件,但我似乎无法弄清楚如果列表被截断并将其全部收集在 Promise 中,如何在其中包含 ContinuationToken。 I'm a novice with JS and could use some help.我是 JS 的新手,可以使用一些帮助。 Here's what I have, so far:到目前为止,这是我所拥有的:

getFiles()
    .then(filterFiles)
    .then(mapUrls)
;

function getFiles(token) {
    var params = {
        Bucket: bucket,
        MaxKeys: 5000,
        ContinuationToken: token
    };
    var allKeys = [];

    var p = new Promise(function(resolve, reject){
    s3.listObjectsV2(params, function(err, data) {
      if (err) { 
        return reject(err);
      }
      allKeys.push(data.Contents)
      if (data.IsTruncated) {
        s3.listObjectsV2({Bucket: bucket, MaxKeys: 5000, ContinuationToken: data.NextContinuationToken})
        console.log('Getting more images...');
        allKeys.push(data.Contents)
      }
      resolve(data.Contents);
    });
  });

  return p;
}

I need the function to continue to run until I've created a list of all objects in the bucket to return.我需要该函数继续运行,直到我创建了要返回的存储桶中所有对象的列表。

You need ContinuationToken the second time only.您只需要第二次使用ContinuationToken

var params = {
    Bucket: bucket,
    MaxKeys: 5000,
};

if (data.IsTruncated) {
    s3.listObjectsV2({...params, ContinuationToken: data.NextContinuationToken})

IMO, this is just a s3 function called twice, more like a nested call. IMO,这只是一个被调用两次的 s3 函数,更像是一个嵌套调用。 Recursion is when a function keeps calling itself until a specified condition is met.递归是指函数不断调用自身直到满足指定条件。

Read more about recursion: https://medium.com/@vickdayaram/recursion-caad288bf621阅读有关递归的更多信息: https : //medium.com/@vickdayaram/recursion-caad288bf621

I was able to list all objects in the bucket using async/await and the code below to populate an array.我能够使用 async/await 和下面的代码列出存储桶中的所有对象来填充数组。

async function getFiles(objects = []) {
    const response = await s3.listObjectsV2(params).promise();
    response.Contents.forEach(obj => filelist.push(obj.Key));
    if (response.NextContinuationToken) {
        params.ContinuationToken = response.NextContinuationToken;
        await getFiles(params, objects);
    }
    console.log(filelist.length)
    return filelist;
}

Thanks to all who helped!感谢所有帮助过的人!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM