0

How can I make request results available as a property of the object? At the moment, console.log(album.artistName) returns undefined. However, if I console.log album.name within the request function, the console will return the album name.

I'd like to be able to create my own object that includes the data points I need so I can access universally.

var request = require('request');

var album = {};
    album.max = 'Max';
    album.artistName = artistName();

function artistName(){
request('https://api.spotify.com/v1/albums/4INyHv55ddXe0A2TNvKezm', function(err, response){
  if(!err && response.statusCode == 200){
    var data = JSON.parse(response.body);
    album.name = data.artists[0].name;
    }
  });
}

console.log(album);
mkayen
  • 27
  • 5

2 Answers2

0

Add this, and restart your app, make a fast request (you have 10 seconds):

setTimeout(function(){
    console.log(album);
}, 10000);

But your question doesn't make much sense. You'll always need something to trigger your code, and when it does you'll not be in a global scope, though as shown here you'll see the global variables.

Gavriel
  • 18,880
  • 12
  • 68
  • 105
0

Answered my own question (I think). This is not happening synchronously. console.log executes before artistName function.

I'd imagine using async, or something similar, will resolve.

mkayen
  • 27
  • 5