I really like programming with node.js
and especially express.js.
Today I run into the typically async issue. I read a lot about these issues and possible solutions, but what is best practice for express.js?
I tried to transfer the callback approach, but it doesn't work. I have to admit, I am a kind of greenhorn in the field and I would appreciate possibly solutions from the community :).
I think the issue in the following code is, that the function call getUserDataFromSpotify(cookieAccessToken)
is async
and the next row can't get the id of the inputData
variable as fast as the function returns a value.
app.get('/landingpage', function(req, res){
var cookieAccessToken = req.cookies.access_token;
var inputData = getUserDataFromSpotify(cookieAccessToken);
res.render('UserProfile', {display_name: inputData.id});
});
function getUserDataFromSpotify(userToken){
var options = {
url: 'https://api.spotify.com/v1/me',
headers: { 'Authorization': 'Bearer ' + userToken },
json: true
};
request.get(options, function(error, response, body) {
console.log(response.statusCode);
console.log(body);
return body;
});
}