【问题标题】:how to use async await in nodejs? error while using async await如何在 nodejs 中使用异步等待?使用异步等待时出错
【发布时间】:2020-07-11 09:46:14
【问题描述】:

我写了谷歌云函数,它从桶中读取文件,然后返回内容。

   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
     ));
    }

我要执行 console.log("outside "+filecontent);只有一次 getFileContent 在处理后返回值。

【问题讨论】:

  • 您有一个不需要的 await 关键字,而在您需要它们的地方缺少 await 关键字。我建议花一些时间来更好地了解 async/await 语法是如何与 Promise 一起工作的。并且一定要了解 Promise 是如何与您正在使用的 API 一起使用的。

标签: node.js async-await google-cloud-functions google-cloud-storage


【解决方案1】:

我在这里犯了一个小错误,必须将await 保留为file.download,正如我上面提到的查询中我已经在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;
      });
    }

进行此更改后,上述代码运行良好。不知道为什么它被否决而不是纠正错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-22
    • 2019-07-20
    • 1970-01-01
    • 2020-03-31
    • 2021-08-27
    • 2017-05-11
    相关资源
    最近更新 更多