Global variable inside require Node.js

Asked

Viewed 131 times

0

I have the following function:

function album(music){
            var album;
            request('http://localhost/socket/source.php?music='+music+'', function (error, response, result){
                data = JSON.parse(result);
                album = data['return'];
            });

            return album;
        }

I would like to call this function return the album value.

I’m trying to call it that:

io.emit('updateNext', {
                    'nextArtist': result['Playlist']['Next'][0]['NextMusic'][0]['Music'][0]['Artist'], 
                    'nextMusic': result['Playlist']['Next'][0]['NextMusic'][0]['Music'][0]['Title'],
                    'nextAlbum': album('eae')
                });

But it’s returning undefined. How can I resolve this?

1 answer

2


Its function album makes a request, which in turn is asynchronous, so you should work with promise or callback. To use promise you can perform the following change in function:

function album(music) {
  return new Promise(function(resolve, reject) {
    request('http://localhost/socket/source.php?music=' + music, function (error, response, result) {
      data = JSON.parse(result);
      resolve(data['return']);
    });
  });
}

And the call:

album('eae').then(function (resultado) {
  io.emit('updateNext', {
    'nextArtist': result['Playlist']['Next'][0]['NextMusic'][0]['Music'][0]['Artist'], 
    'nextMusic': result['Playlist']['Next'][0]['NextMusic'][0]['Music'][0]['Title'],
    'nextAlbum': resultado
  });
});
  • Thank you very much friend. It helped me a lot!

  • @Paulosérgiofilho if the answer solved your problem don’t forget to accept it as correct by clicking the accept button next to the answer

  • 1

    I am only waiting for the time necessary to accept. It cannot be immediately s:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.