Having trouble with the AWS S3 getSignedUrl looping function?

Could you assist me in sending two S3 pre-signed URLs for every key found in the [user.idKey, user.selfieKey] array within my Express route?

I have confirmed that S3 is successfully obtaining the pre-signed URLs as they are logging to the console using the callback console.log(url).

I attempted to use "await" before the getSignedUrl method, but it seems like it may not work with S3...any suggestions on what I might be doing incorrectly?

Your help is much appreciated!


router.get(`/api/verification/load`, auth, async (req, res) => {

  try {
    const user = await User.findOne({ GETS A USER })

    let urlArray = []

    const keyArray = [user.idKey, user.selfieKey]
   
    for (const key in keyArray) {
      s3VerificationBucket.getSignedUrl(
        "getObject",
        {
          Bucket: "app-verification",
          Key: key,
          Expires: 30,
        },
        (err, url) => urlArray.push(url) // urls are logged when console.log(url) is used 
      )
    }

    if (urlArray.length === 0) {  
      console.log("URL ARRAY EMPTY") -> RETURNS "URL ARRAY EMPTY"
    }

    const idUrl = urlArray[0]
    const selfieUrl = urlArray[1]

    res.send({ user, idUrl, selfieUrl })
  } catch (err) {
    res.status(500).send()
  }
})


Answer №1

While your response is being sent synchronously, the signing of your links is done asynchronously. This means that the array is populated after you have already sent the response.

Instead, try using

s3VerificationBucket.getSignedUrl(...).promise()
to obtain a promise for each operation.

Utilize Promise.all(...) to ensure that you wait for the results of all operations before sending a response.

Remember to only send a response using res.send(...) once you have completed all asynchronous tasks.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implement a 'mock' singleton decorator for the Node class that includes a required initialization method

(Disclaimer: Previous question was deleted due to new fundamental problems, so attempting again with a more logical question). I have a class that requires specific initialization properties: var CustomRequest = require('./request'), ok = r ...

Executing JavaScript code using an HTML form submission

Greetings, I have implemented an HTML form on my website for user login using AJAX (jQuery), but I am encountering some issues. Below is the JavaScript code: function validateLoginDetails() { $('[name=loginUser]').click(function() { ...

accessing the php script within a node environment

Hey there! I'm currently working on creating a chat system using socket.io, express.io, and node.js. So far, everything has been going smoothly as I've been following the documentation provided by these tools. However, when I attempt to integrat ...

Issue encountered while attempting to animate a spherical object within a confined space in Three.js

I'm fairly new to three.js and encountering issues while attempting to animate a sphere moving through a space. My approach involves creating a new sphere and using new THREE.Vector3().randomDirection() to set it in motion. The sphere is meant to mov ...

Stripping CSS from my HTML using TinyMCE

I have created a custom Javascript function that retrieves the content of an HTML file from my server and then integrates it into a TinyMCE editor. Here is the function: function LoadTemplate(url) { $.post(url, function (data) { // Access the ...

Kendo's data-bind onclick feature functions properly on web browsers but fails to work on mobile devices

As a newcomer to Kendo and JavaScript, I may be missing something obvious... In one of my list entries, I have a simple call like this: <li style="margin: 0.5em 0 0.5em 0"> <a href="#transaction-details" data-bind="click: onB ...

Encountering an unforeseen identifier error while attempting to install GitHub using

I am facing an issue with my GitHub repo where I am trying to install Clockwork SMS using npm. However, the console is showing an error message "Uncaught SyntaxError: Unexpected identifier". You can find the website here: . To explain further, I am workin ...

jQuery Animated List - Nested items are unresponsive to clicks

Looking to create a dynamic nested list using jQuery for animations, but unsure of the best approach. Currently, I'm adjusting the length of the parent list item and revealing the nested items. The issue is that the parent item's length covers ...

Enhancing the utilization of the express.js module

It can be quite frustrating that when you need to use a node module, you have to manually install it, require it, and add it to the package.json file. Conversely, if you decide not to use it, you have to go through the same process in reverse. Is there an ...

An Unexpected Token Leads to a SyntaxError in Jest's CSS-Modules

I have successfully configured my jest to allow the usage of static files by following their detailed documentation. However, despite implementing the instructions correctly, I am still encountering an error: What steps can I take to resolve this issue an ...

Making Jquery functions work with Internet Explorer (including toggle and animate)

Why is this jQuery code snippet not functioning as expected in Internet Explorer? It works flawlessly across all Webkit browsers. $('#logo').toggle(function() { $('#about').animate({'top': '-400px'},'slow&a ...

The local variable within the Angular constructor is not initialized until the ngOnInit() function is invoked

I am encountering difficulties with making backend calls from Angular. In my component, I am fetching the "category" parameter from the URL as shown below: export class ProductsComponent{ productList = [] category = "" $params; $products ...

Automate the compilation of SASS files from designated sources to separate directories

Within my /source/sass/skin1_settings.scss file, I have imports from /vendors/foundation/, specific style settings, and the app.scss. I want to compile this using node.JS directly into /skin/skin1/css/app.css, how can I achieve this? Please note: The same ...

Display the invoice bill using text in a Vue component

Hello, I am looking to print an invoice that resembles the one shown in this picture https://i.sstatic.net/6mzwe.jpg However, when I try to print it, I get a different output with some additional elements https://i.sstatic.net/uaKZC.jpg I am using vue. ...

How can I style the options and optgroups of a select dropdown with CSS, focusing on padding and margins?

In my experience, I have found that padding or margin CSS properties only seem to affect the appearance of options within the select menu in Firefox browser. I attempted the same styling in Internet Explorer and Chrome but it did not have any effect. Is ...

Mobile website menu selection

I want to create a select menu for my mobile website. I have added the select HTML code to my page. <select id="menu_mobile"> <option value="" selected="selected">Navigation</option> <option value="http://example.com/about"> Ab ...

What is the process of invoking Link manually in React-router?

I am working on a component that is passed a <Link/> object from react-router as a prop. When the user clicks on a 'next' button within this component, I need to manually trigger the <Link/> object. Currently, I am using refs to acce ...

retrieve only the following occurrence throughout the entire file

I am looking to target only the first occurrence of an element in the document after a clicked element. Here is my current approach: $('.class').click(function(){ var x = $(this).nextAll('.anotherclass').first(); //do something ...

Removing API request in React.js

My approach: deleteSample = () => { this.sampleService .deleteCall(this.props.id) .then((response) => { window.location.reload(false); }) .catch((error) => { console.log ...

When there is an expensive calculation following a Vue virtual DOM update, the update may not be

Currently, I am facing an issue with adding a loading screen to my app during some heavy data hashing and deciphering processes that take around 2-3 seconds to complete. Interestingly, when I removed the resource-intensive parts, the screen loads immediate ...