我们可以在 firebase 的云函数中使用 async/await 吗?

Ama*_*ngh 8 javascript node.js firebase google-cloud-functions

我必须调用以下函数: 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();
}
Run Code Online (Sandbox Code Playgroud)
async function saveApiDataToDb() {
  await getMatchDataApi();
  var name = playerName;
  console.log("Aman Singh", name);
}
Run Code Online (Sandbox Code Playgroud)

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

exports.storeMatchData = functions.https.onRequest((request, response) => {
   saveApiDataToDb()
});
Run Code Online (Sandbox Code Playgroud)

Moh*_* G. 5

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

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);
            });
        });
    }
Run Code Online (Sandbox Code Playgroud)