1

I am missing something simple in Node, I have a function that needs to be exported, and return a value, async. I am not sure how in Node to have it "wait" before returning the value, I am apparently spoiled with front end javascript and databinding...

The code below will not wait for users to have the data back (pusher is a rest call) so it is always undefined.

exports.getMembers = function(channel) {
    var users;
    pusher.get( { path: '/channels/'+channel+'/users', params: {} },
            function( error, request, response ) {
                if( response.statusCode === 200 ) {
                    var result = JSON.parse( response.body );
                    users = result.users;
                    return users;
                }
                else {
                    console.log(error);
                }
            }
    );
        //return users;
};
TrikinCurt
  • 108
  • 1
  • 5
  • You will need to use a callback. See [this answer](http://stackoverflow.com/a/14220323/816620) which is about client-side Ajax, but the async concept is the same and it explains your various options for getting an async value out to some other code. – jfriend00 Feb 10 '15 at 07:37

1 Answers1

3

I think this is just a fundamental misunderstanding about how async works. There are several ways you can approach this depending on what you would like to happen after the "wait" period. I don't know what action you want to take place after you call getMembers, but for arguments sake let's just simply use a console message.

Method 1: Error-First Callbacks

module.exports.getMembers = function(channel, callback) {

  pusher.get( { path: '/channels/'+channel+'/users', params: {} },
        function( error, request, response ) {
            if( !error && response.statusCode === 200 ) {
                var result = JSON.parse( response.body );
                //found our users, return them as 2nd param
                return callback(null, result.users);
            }
            else {
                //something went wrong, fail out
                return callback(error);
            }
        });

}

Usage:

var getMembers = require('mymodule').getMembers;

getMembers('#channelNum', function(err, results) {
   if(err) return console.error(err);
   console.log('Found %s users', results.length);
});

Method 2: Promises

This is my personal choice when dealing with async, because I find it cleaner. I am leaving out the code to keep this post short.

sctskw
  • 1,588
  • 1
  • 12
  • 14