Node-soap client and scope of the callback

I'm using the node-soap client from milewise (create API by the way), but I have some difficulties to get the results of the callback to the right scope.

Here is the code I have for now:

function generateSoapRequest(req, res, next)
{ 
    soap.createClient('http://127.0.0.1:' + cfg.service_port + cfg.service_url_path,
    function(err, client) {
        client.CXIf.CXIf.CXProcessXML(
            {"XMLRequestData": {"CXLogon": {"UserID":"1901007", "Password":"2580", "LogonType":11 } } }, 
            function(err, result, body) {
            if (err) {
                console.log(err);
                return;
            }
            console.log(result);

            var cxresponse = result.XMLResponse[0].CXResponse;
            console.log('SessionID:' + cxresponse.SessionID + ' SessionInstanceID:' + cxresponse.SessionInstanceID);
        });
    });
}

function getVoiceMailInformation(req, res, next) {
    var cxresponse = generateSoapRequest(req, res, next);
    var something = doSomethingNext(cxresponse);
}

function doSomethingNext(cxresponse){....; return something;}

Basically, when I launch the getVoiceMailInformation(), it creates a soap client and request some information through the generateSoapRequest(). The next step would be to get the result of that function (not implemented in the code above, because I don't know how) and do something else.

My problem is soap.createClient is asynchronous, so the callback is fired well after the function is complete.

What would be the best approach ? (Maybe it's something trivial, but the scope of an anonymous function in javascript is something that is killing me.)

Any help will be very appreciated.

Basically you can't do something like:

var cxresponse = generateSoapRequest(req, res, next);

because the function you're calling invokes asynchronous code, and therefore can't return a value that's determined by that code. The normal way around this is to give the function an extra callback parameter for a function that will be called with the result once the result becomes available. It doesn't have to be an anonymous function; it can be a named function. In your case, (assuming you've modified generateSoapRequest to take a callback as its fourth argument and call it when the results are ready, you could write

generateSoapRequest(req, res, next, doSomethingNext);

and then doSomethingNext will be called with cxresponse as an argument. Of course, since doSomethingNext also gets called asynchronously, it can't return a value either, so you'll have to apply the same technique to it.

The async module can make this sort of thing easier: in particular, its "waterfall" pattern is useful when you have a bunch of functions that have to run in sequence, each being called back from the previous one.