898247
898247

Reputation: 10606

confusion about node.js scoping

I'm writing a client for mpd (music player daemon) with node, using the node-mpdsocket library, but I appear to have run into a bit of confusion early on. In this example, response is an object, and response['state'] should return a string.

var togglePause = function() {
  var mpdState;

  mpd.send('status', function(response) {
    mpdState = response.state;

    // Here, console.log(mpdState) returns mpd's state correctly
    console.log(mpdState);
  });

  // Here, undefined is returned regardless of mpd's actual state
  console.log(mpdState);
}

I expected mpdState to return a string in both instances because both places where console.log are called are within the same function. However, this does not appear to be the case.

Upvotes: 0

Views: 57

Answers (1)

Andrew Eisenberg
Andrew Eisenberg

Reputation: 28737

The callback passed to mpd.send is being invoked asynchronously. So, the second console.log statement is being called before the callback is ever run. The console.log statement inside the callback has the correct value as you can see.

The code you are running is behaving as expected.

Upvotes: 1

Related Questions