0

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.

Randall Ma
  • 10,486
  • 9
  • 37
  • 45
  • 1
    In the `mpd.send` callback function where you set `mpdState` is actually asynchronous. So your last `console.log` actually executes first and it is `undefined` at the point of time. – Kamrul Jun 30 '14 at 03:51
  • 1
    The issue isn't scope. `mpdState` is in scope to throughout `togglePause`. The issue is execution order. Since `mpd.send()` is asynchronous, `togglePause` doesn't execute entirely top-to-bottom. Related: [How to return the response from an Ajax call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – Jonathan Lonowski Jun 30 '14 at 03:52
  • You can't return a value that is set from an asynchronous function. You have to get that value using callbacks. One of the most searched questions in JavaScript arty stack overflow – Ruan Mendes Jun 30 '14 at 03:53
  • Great, thanks guys! If someone wants to submit one of your comments as an answer, I'd love to accept it. – Randall Ma Jun 30 '14 at 03:55

1 Answers1

1

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.

Andrew Eisenberg
  • 28,387
  • 9
  • 92
  • 148