I've currently got a expressJS app and I'm trying to retrieve information from an API using the getStats function. However, the profile route I've written seems to be multiple nested callbacks. How would I prevent this? Is there a way to make it get all of the stats, then assign them to variables after they all of the stats are retrieved?
function getStats(access_token, time_range, x, callback) {
var stats = [];
var options = {
url: 'www.example.com',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
json: true
}
request(options, function(error, response, body) {
if (!error && response.statusCode == 200) {
for (i = 0; i < body.items.length; i++) {
stats.push(body.items[i].name);
}
return callback(stats);
}
})
}
app.get('/profile', function(req, res) {
var access_token = 1234;
getStats(access_token, 's', 'x', function(a){
console.log(a);
getStats(access_token, 's', 'y', function(b){
console.log(b);
getStats(access_token, 'm', 'x', function(c){
console.log(c);
getStats(access_token, 'm', 'y', function(d){
console.log(d);
getStats(access_token, 'l', 'x', function(e){
console.log(e);
getStats(access_token, 'l', 'y', function(f){
console.log(f);
res.send(a + "\n" + b + "\n" + c + "\n" + d + "\n" + e + "\n" + f);
});
});
});
});
});
});
});