I'm learning Node JS as well as how to access an API's information, and I've come across a problem where when I push values to an array, the info never gets added globally.
So let's say I have var albIds= new Array(5)
, the values never get added. Through looking at this and this I now know that the issue is that the information never gets into the array by the time I call it, due to the synchronous code being done first, however, I am confused at how to make the synchronous wait for the asynchronous to complete.
my code so far.
//prints out albums 1-5 id's
var id = '3TVXtAsR1Inumwj472S9r4';
var albIds= new Array(5);
async function getAlbums(i) {
var authOptions = {
url: 'https://accounts.spotify.com/api/token',
headers: {
'Authorization': 'Basic ' + (new Buffer.from(client_id + ':' + client_secret).toString('base64'))
},
form: {
grant_type: 'client_credentials'
},
json: true
};
request.post(authOptions, function(error, response, body) {
if (!error && response.statusCode === 200) {
// use the access token to access the Spotify Web API
// const querystring = require('querystring');
const data = {
market: "US",
limit: "5"
};
const q = querystring.stringify(data);
var token = body.access_token;
var options = {
url: 'https://api.spotify.com/v1/artists/'+id+'/albums?'+q,
headers: {
'Authorization': 'Bearer ' + token
},
json: true
};
request.get(options, function(error, response, body)
{
for(var i = 0; i<5;i++)
{
albIds.push(body.items[i].id);
}
});
}
})
};
async function fetchUsers()
{
for(var i = 0;i<5;i++)
{
await getAlbums(i);
console.log(albIds[i]);
}
}
fetchUsers();
Any help appreciated. For reference, I'm using Spotify's API