【问题标题】:Can we use async/await in cloud functions in firebase?我们可以在 firebase 的云功能中使用 async/await 吗?
【发布时间】:2020-03-22 20:50:29
【问题描述】:

我必须调用函数:getMatchDataApi() 和 saveApiDataToDb()。 getMatchDataApi() 函数从 api 返回值,saveApiDataToDb() 函数用于将 getMatchDataApi() 值存储到 firestore 数据库中。

function getMatchDataApi() {
  var options = {
    method: "GET",
    hostname: "dev132-cricket-live-scores-v1.p.rapidapi.com",
    port: null,
    path: "/scorecards.php?seriesid=2141&matchid=43431",
    headers: {
      "x-rapidapi-host": "dev132-cricket-live-scores-v1.p.rapidapi.com",
      "x-rapidapi-key": "63e55e4f7fmsh8711fb1c0bd9ec2p1d8b4bjsne2b8db0a1a82"
    },
    json: true
  };
  var req = http.request(options, res => {
    var chunks = [];

    res.on("data", chunk => {
      chunks.push(chunk);
    });

    res.on("end", () => {
      var body = Buffer.concat(chunks);
      var json = JSON.parse(body);
      playerName = json.fullScorecardAwards.manOfTheMatchName;
      console.log("player name", playerName);
    });
  });
  req.end();
}
async function saveApiDataToDb() {
  await getMatchDataApi();
  var name = playerName;
  console.log("Aman Singh", name);
}

我在这里使用异步功能。所以首先我希望它应该首先执行这个 getMatchDataApi() 并返回值,然后它应该在这个函数 saveApiDataToDb() 中打印值。 然后我调用 saveApiDataToDb() 如下:

exports.storeMatchData = functions.https.onRequest((request, response) => {
   saveApiDataToDb()
});

【问题讨论】:

  • 我是 Firebase 中云功能的新手。请帮助任何人。提前致谢
  • getMatchDataApi 没有返回任何承诺,所以你不能等待它。另外,playerName 是全局变量吗?
  • 你的函数应该返回一个承诺,当所有异步工作完成时解决。 firebase.google.com/docs/functions/terminate-functions

标签: javascript node.js firebase google-cloud-functions


【解决方案1】:

我尝试使用云函数中的 Promise 来解决我的问题。所以它可以帮助某人。 这是我的云功能

exports.storeMatchData = functions.https.onRequest((request, response) => {
  a().then(
    result => {
      saveApiDataToDb(result);
    },
    error => {}
  );
});

这是我调用 api 并首先解析其数据的函数

var options = {
  method: "GET",
  hostname: "dev132-cricket-live-scores-v1.p.rapidapi.com",
  port: null,
  path: "/scorecards.php?seriesid=2141&matchid=43431",
  headers: {
    "x-rapidapi-host": "dev132-cricket-live-scores-v1.p.rapidapi.com",
    "x-rapidapi-key": "63e55e4f7fmsh8711fb1c0bd9ec2p1d8b4bjsne2b8db0a1a82"
  },
  json: true
};

var options1 = {
  method: "GET",
  hostname: "dev132-cricket-live-scores-v1.p.rapidapi.com",
  port: null,
  path: "/matches.php?completedlimit=5&inprogresslimit=5&upcomingLimit=5",
  headers: {
    "x-rapidapi-host": "dev132-cricket-live-scores-v1.p.rapidapi.com",
    "x-rapidapi-key": "63e55e4f7fmsh8711fb1c0bd9ec2p1d8b4bjsne2b8db0a1a82"
  }
};

var a = function getMatchDataApi() {
  // Return new promise
  return new Promise((resolve, reject) => {
    // Do async job

    let firstTask = new Promise((resolve, reject) => {
      var req = http.request(options, res => {
        var chunks = [];
        var arr = [];

        res.on("data", chunk => {
          chunks.push(chunk);
        });

        res.on("end", () => {
          var body = Buffer.concat(chunks);
          var json = JSON.parse(body);
          const playerName = json.fullScorecardAwards.manOfTheMatchName;
          resolve(playerName);
        });
      });
      req.end();
    });

    let secondTask = new Promise((resolve, reject) => {
      var req = http.request(options1, res => {
        var chunks = [];
        var arr = [];

        res.on("data", chunk => {
          chunks.push(chunk);
        });

        res.on("end", () => {
          var body = Buffer.concat(chunks);
          var json = JSON.parse(body);
          const playerName = json;
          resolve(playerName);
        });
      });
      req.end();
    });

    Promise.all([firstTask, secondTask]).then(
      result => {
        resolve(result);
      },
      error => {
        reject(error);
      }
    );
  });

};

这是我将在此函数中解析后使用 getMatchDataApi() 值的函数。

function saveApiDataToDb(data) {
  console.log("Name of player", data[0]);
}

【讨论】:

    【解决方案2】:

    是的,您可以在云功能中使用 async/await。但是,您无法在 Spark 计划(免费计划)中访问/获取谷歌服务器之外的数据。 希望这会有所帮助。

    像这样修改你的functions/index.js文件:

        const functions = require('firebase-functions');
        const request = require('request');
    
    
        exports.storeMatchData = functions.https.onRequest( async (req, res) => {
            let body = '';
            await getMatchDataApi().then(data => body = data).catch(err => res.status(400).end(err));
    
            if (!body) {
                return res.status(404).end('Unable to fetch the app data :/');
            }
            // let json = JSON.parse(body);
            // playerName = json.fullScorecardAwards.manOfTheMatchName;
            // console.log("Aman Singh", playerName);
            res.send(body);
        });
    
        function getMatchDataApi() {
            const options = {
                url: 'https://dev132-cricket-live-scores-v1.p.rapidapi.com/scorecards.php?seriesid=2141&matchid=43431',
                headers: {
                    "x-rapidapi-host": "dev132-cricket-live-scores-v1.p.rapidapi.com",
                    "x-rapidapi-key": "63e55e4f7fmsh8711fb1c0bd9ec2p1d8b4bjsne2b8db0a1a82"
                },
            };
    
            return cURL(options);
        }
    
    
    
        function cURL(obj, output = 'body') {
            return new Promise((resolve, reject) => {
                request(obj, (error, response, body) => {
                    if (error)
                        reject(error);
                    else if (response.statusCode != 200)
                        reject(`cURL Error: ${response.statusCode} ${response.statusMessage}`);
                    else if (response.headers['content-type'].match(/json/i) && output == 'body')
                        resolve(JSON.parse(body));
                    else if (output == 'body')
                        resolve(body);
                    else
                        resolve(response);
                });
            });
        }
    

    【讨论】:

    • 我有大火计划。那么我如何在上面提到的代码中使用 async/await。
    • 所以我想做的是: 1. getMatchDataApi() 这个函数应该首先运行并返回“playerName”值 2.saveApiDataToDb() 然后这个函数应该执行以将“playerName”值存储到我的分贝。所以我必须使用异步/等待功能。所以我很困惑如何使用它?
    • 在这种情况下,您必须在 getMatchDataApi() 函数中使用 Promise。最好使用https://www.npmjs.com/package/request-promisehttps://www.npmjs.com/package/axios
    • 红利:官方 firebase/functions-samples
    • 我浏览了这些函数示例以及您提供的链接。你能帮我写代码如何在上面的代码中使用promise或async/await吗?这真的会有所帮助。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-18
    • 1970-01-01
    • 2018-05-26
    • 1970-01-01
    • 2019-11-10
    • 2016-02-24
    • 2012-06-18
    相关资源
    最近更新 更多