我们可以在Firebase的云函数中使用异步/等待吗?

时间:2019-11-27 10:15:09

标签: 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();
}
async function saveApiDataToDb() {
  await getMatchDataApi();
  var name = playerName;
  console.log("Aman Singh", name);
}

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

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

2 个答案:

答案 0 :(得分:0)

是的,您可以在云功能中使用异步/等待。但是,您无法在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);
            });
        });
    }

答案 1 :(得分:0)

我尝试在云函数中使用promise解决我的问题。这样可以帮助某人。 这是我的云功能

nullptr

这是我调用api并首先解析其所需数据的功能

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

在解决此功能后,我将在其中使用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 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);
      }
    );
  });

};