0

I'm having an issue with getting the correct value returned with an async function. Here's the code . I'm getting the signedUrls after uploading an image and that works correctly, but it is getting to that line too late after the return. The value I want to return is "signedUrls[0]" but right now it is returning something different. I'm not sure what I'm missing to get it to return the correct value. Thanks so much!

var uploadedUrl = response.data.pipe(writeStream)
      .on('finish', async () => {
           console.log('Successfully uploaded image: ');
              
           signedUrls = await file.getSignedUrl({
                action: 'read',
                expires: '03-09-2491'
           });
           console.log("signedUrls: ",signedUrls);
           return signedUrls[0];
      })
      .on('error', () => {
           console.log('Error uploading image');
           return "";
       });
console.log("uploadedURL: ",uploadedUrl);
Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
AWood
  • 21
  • 1
  • 2

1 Answers1

-1

The problem is not that the return value comes too late. The problem is the .on listener is simply a callback that gets triggered when the event happened and does not return the value of the callback.

What you can do is convert the RHS to a promise:

var uploadedUrl = await new Promise((resolve, reject) => {
  response.data.pipe(writeStream)
      .on('finish', async () => {
           console.log('Successfully uploaded image: ');
              
           signedUrls = await file.getSignedUrl({
                action: 'read',
                expires: '03-09-2491'
           });
           console.log("signedUrls: ",signedUrls);
           resolve(signedUrls[0]);
      })
      .on('error', () => {
           console.log('Error uploading image');
           reject();
       });
});
console.log("uploadedURL: ",uploadedUrl);

Obviously, in order to use await, the above code should be in an async function.

technophyle
  • 7,972
  • 6
  • 29
  • 50
  • 1
    Avoid the [`Promise` constructor antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it)! This does not handle errors from `getSignedUrl`. Move that call outside of the `finish` handler, just after the `await new Promise()`. Only call `resolve` and do nothing else from the asynchronous event. – Bergi Jul 18 '23 at 20:11