Trouble dealing with asynchronous non-blocking model

43 views
Skip to first unread message

Haroon Dilshad

unread,
Sep 25, 2014, 1:09:57 PM9/25/14
to nod...@googlegroups.com
Hello everyone, I'm having trouble with getting around asynchronous model of node, I have this function
 function getstream() {

                           console.log('calling testAvail, Avail value is:' + available);
                            testAvailability();
                        console.log('Available:'+available);
                        if (available || SelfSharing) {

// Do something
                                setDefaults();


                                return;
                            }
     }

which calls testAvailability() function defined as

    function testAvailability()
    {
        console.log('entered test');
        var stat;
        var socket = io.connect('http://somedomain.com');
        socket.on('error', function() {

            console.log('There was an error at server end please try again');
//            chrome.runtime.reload();

            setTimeout(chrome.runtime.reload(),3000);
            //here i change options
            //socket = io.connect(host, options);
        });
        socket.emit('available');
        socket.on('available', function (status) {
            console.log('got status from server which is:'+ status);
            available=status;
            console.log("inside the socket.on"+available);
            console.log('leaving test, do you see any got status above?');
        });

    }


Now in this first function I need the available variable's value but due to async nature, my first function continues without getting the value of available could someone please suggest some work around? code would help.
Thanks

Ryan Schmidt

unread,
Sep 25, 2014, 3:33:08 PM9/25/14
to nod...@googlegroups.com
You need to rethink both of these functions to be asynchronous, and also to not use global variables. Each function will accept a callback, which the function will call when it it's ready to do so.


Reply all
Reply to author
Forward
0 new messages