简体   繁体   English

如何在nodejs中使用异步等待? 使用异步等待时出错

[英]how to use async await in nodejs? error while using async await

I have written google cloud function, which reads file from the bucket and then return the content.我编写了谷歌云函数,它从存储桶中读取文件,然后返回内容。

   async function getFileContent(fileName, bucketName) {
      const storage = new Storage();
      const file = await storage.bucket(bucketName).file(fileName);
      file.download(function(err, contents) {
           console.log("file err: "+err);
           console.log("file data: "+contents); //contents is displaying data here
          return contents;
      });
    }
//cloud function starts
    exports.getdata = async function(req, res) {
      var filecontent = await getFileContent("file1", "bucket1");
      console.log("outside "+filecontent); //displaying as undefined
     ));
    }

I want to execute console.log("outside "+filecontent);我想执行 console.log("outside "+filecontent); only once the getFileContent returns value after processing.仅当 getFileContent 在处理后返回值时。

I have done small mistake here, have to keep await for file.download where as in the query i have mentioned above i have given await at storage.bucket(bucketName).file(fileName);我在这里犯了一个小错误,必须为file.download保留await ,在我上面提到的查询中,我在storage.bucket(bucketName).file(fileName);给出了 await storage.bucket(bucketName).file(fileName);

 async function getFileContent(fileName, bucketName) {
      const storage = new Storage();
      const file = storage.bucket(bucketName).file(fileName);
      content = await file.download(function(err, contents) {
           console.log("file err: "+err);
           console.log("file data: "+contents); //contents is displaying data here
          return contents;
      });
    }

the above code is working fine after making this change.进行此更改后,上述代码工作正常。 Not sure why it is down voted instead of correcting the mistake.不知道为什么它被否决而不是纠正错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM