Search code examples
javascriptgoogle-cloud-platformasync-awaitanonymous-function

Return data from async anonymous function that is an argument to a non-anonymous function


I'm attempting to return the contents argument of an async anonymous function. The contents argument is populated within the anonymous functions block but on return it is undefined.

I've attempted awaiting the entire thing to no effect:

  const file = 
     await storage.bucket(bucketName).file("myImage.jpg").download(async 
        function(err, contents) {
          return contents;
     });
 <file is undefined>

I've also attempted awaiting the contents: return await contents; with the same result.

This is within a GCP cloud function but I'm sure I'm just screwing up the JS here.

Thanks in advance for the guidance.


Solution

  • It doesn't look like you're using the API correctly. There's no need to pass a callback function if you're going to use the promise returned by download().

    If you want to download the contents of a storage object into memory, it works like this:

        const contents = await storage.bucket(bucketName).file(fileName).download();
    
        console.log(
          `Contents of gs://${bucketName}/${fileName} are ${contents.toString()}.`
        );
    

    This was taken directly from example code from Google.

    See also the API documentation for download().