Así que estoy usando una API de partidos de fútbol en vivo
Estoy tomando lo que necesito de la respuesta json y almacenándolo en una matriz
Quiero devolver la matriz como una respuesta json cuando visito una ruta determinada
aquí está el código
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("--------------------------------------------"); } });}
Supongo que su pregunta real es cómo devolver los datos desde el interior de la función getData() . Si ese es el caso, entonces solo necesita usar una Promesa esperable:
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();Y luego lo usarás de manera similar a esto:
const serverData = await getData(); console.log(serverData); // OK