-1

So Im using a football live matches api

Im taking what i need from the json response and storing it in an array

I want to return the array as a json response when i visit a certain route

Here's the code

var request = require('request');

exports.data = function getData(){


const options = {
  method: 'GET',
  url: 'https://elenasport-io1.p.rapidapi.com/v2/inplay',
  qs: {page: '1'},
  headers: {
    'x-rapidapi-host': 'elenasport-io1.p.rapidapi.com',
    'x-rapidapi-key': 'mykey',
    useQueryString: true
  }
};

request(options, function (error, response, body) {

    var liveMatches = [];
        data = JSON.parse(body);
        var matchesList = data['data'];

    for(let i = 0; i < matchesList.length; i++){
            
             liveMatches.push(
             {
                homeName : matchesList[i]['homeName'],
                awayName : matchesList[i]['awayName'],
                elapsed : matchesList[i]['elapsed'],
                team_home_goals : matchesList[i]['team_home_90min_goals'],
                team_away_goals : matchesList[i]['team_away_90min_goals'],
                createdAt : Date.now()
             }
                );
        }

        for (let j= 0; j<liveMatches.length;j++){
            console.log(liveMatches[j]);
            console.log("--------------------------------------------");
        }

});

}

Fiodorov Andrei
  • 1,778
  • 1
  • 11
  • 26
  • What do you mean with `return`? the `request` function you're using has a callback function, it does not return a value to its caller, so you run that function with the data you want that function to receive. If you want that, using [the node version of the fetch API](https://www.npmjs.com/package/node-fetch) is a better idea. Also, why would you send on JSON instead of actual JS data? JSON is for when you need to package up and send JS object data out of JS to something else. As long as you're in JS, don't turn anything into JSON. – Mike 'Pomax' Kamermans Nov 20 '21 at 16:49
  • And what's the problem? That's a quite common task, hence you should be able to find a solution in the WWW or here on SO. – Andreas Nov 20 '21 at 16:49
  • 1
    `JSON.stringify('liveMatches')`? – Randy Casburn Nov 20 '21 at 16:49
  • Perhaps you need this [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call/14220323#14220323). – jfriend00 Nov 20 '21 at 16:56

1 Answers1

0

I guess that your actual question is how to return the data from inside the getData() function. If that's the case, then you just need to use an awaitable Promise:

var request = require('request');

function getData() {
  const options = {
    method: 'GET',
    url: 'https://elenasport-io1.p.rapidapi.com/v2/inplay',
    qs: { page: '1' },
    headers: {
      'x-rapidapi-host': 'elenasport-io1.p.rapidapi.com',
      'x-rapidapi-key': 'mykey',
      useQueryString: true,
    },
  };

  return Promise((resolve) => {
    request(options, function (error, response, body) {
      data = JSON.parse(body);
      const matchesList = data['data'];

      const liveMatches = [];
      for (let i = 0; i < matchesList.length; i++) {
        liveMatches.push({
          homeName: matchesList[i]['homeName'],
          awayName: matchesList[i]['awayName'],
          elapsed: matchesList[i]['elapsed'],
          team_home_goals: matchesList[i]['team_home_90min_goals'],
          team_away_goals: matchesList[i]['team_away_90min_goals'],
          createdAt: Date.now(),
        });
      }

      resolve(liveMatches); // <--- this is the important part
    });
  });
}

exports.data = getData();

And then you'll use it in similarly to this:

const serverData = await getData();

console.log(serverData); // OK
Mihai Paraschivescu
  • 1,261
  • 13
  • 12