Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

132
Visualizações
Returning an array as a json response

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

});

}

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

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
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda