Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
106
rated 0 times [  107] [ 1]  / answers: 1 / hits: 7145  / 5 Years ago, wed, december 18, 2019, 12:00:00

In fact, I begin with node.js. And i don't know how to pass the response to a variable. I don't want to make my code in my response.. I try a lot of things but nothing is working.. I know is a simple question.. but it's not working



const axios = require('axios');
var test = null
function getLeagues () {
axios.get('https://api-football-v1.p.rapidapi.com/v2/fixtures/league/525?timezone=Europe/Paris', {
headers: {
'X-RapidAPI-Key': '<my-api-key>'
}
})
.then(response => {

test = response.data.api.fixtures

return response.data.api.fixtures
})
.catch(error => {
console.log(error);
});
}

console.log(test)


More From » node.js

 Answers
5

You should use promises and wait for the response to be ready:



const axios = require('axios');

function getLeagues () {
return axios.get('https://api-football-v1.p.rapidapi.com/v2/fixtures/league/525?timezone=Europe/Paris', {
headers: {
'X-RapidAPI-Key': 'foo-api-key'
}
})
.then(response => {
return response.data.api.fixtures
})
.catch(error => {
console.log(error);
return Promise.reject(error);
});
}

getLeagues().then(response => {
console.log(response);
});


Or, using async/await:



const consoleLeagues = async () => {
const leagues = await getLeagues();
console.log(leagues);
};

consoleLeagues();

[#5288] Monday, December 16, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jarod

Total Points: 62
Total Questions: 111
Total Answers: 83

Location: Saint Vincent and the Grenadines
Member since Sat, Sep 11, 2021
3 Years ago
jarod questions
Sun, Aug 23, 20, 00:00, 4 Years ago
Sun, Apr 26, 20, 00:00, 4 Years ago
Sat, Sep 21, 19, 00:00, 5 Years ago
;