代码之家  ›  专栏  ›  技术社区  ›  Pis7ftw

从异步匿名函数返回数据,该函数是非匿名函数的参数

  •  0
  • Pis7ftw  · 技术社区  · 2 年前

    我正试图返回一个异步匿名函数的contents参数。contents参数填充在匿名函数块中,但返回时未定义。

    我试图等待整个事情,但没有效果:

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

    我也尝试过等待内容: return await contents; 具有相同的结果。

    这是在GCP云函数中,但我确信我只是把这里的JS搞砸了。

    提前感谢您的指导。

    1 回复  |  直到 2 年前
        1
  •  1
  •   Doug Stevenson    2 年前

    看起来您没有正确使用API。如果要使用由返回的promise,则不需要传递回调函数 download() .

    如果您想将存储对象的内容下载到内存中,其工作方式如下:

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

    这是直接从 example code from Google .

    另请参阅 API documentation for download() .