Skip to content Skip to sidebar Skip to footer

Async / Await Looping Through Array Of To Get S3 Signed Url's

I've written the following code. The input (result) is an array of file names that exist on an S3 bucket. What I'm hoping to do is loop through that list and retrieve a signed UR

Solution 1:

let result = [{ fileName: "dog.jpg" },{ fileName: "cat.jpg"}];

async function getSignedUrl(key){
    return new Promise((resolve,reject) => {
      let params = { Bucket: bucketName, Key: key };
      s3.getSignedUrl('getObject', params, (err, url) => {
        if (err) reject(err);
        resolve(url);
      });
});
}

async function process(items) {
  for (let item of items) {
    const signedUrl = await getSignedUrl(item.fileName);
    item.url = signedUrl;
  }
  return items;
}


process(result).then(res => {
  console.log(res);
});

NOTE: it's better to use Promise.all() if you are processing an array of possible promises since await stops the execution of that code in async function (not the event loop) even though it's a none blocker function. Doing parallel request is much faster in this scenario


Post a Comment for "Async / Await Looping Through Array Of To Get S3 Signed Url's"