node.jsnode-soap

need to wait for soapClient result


Hi All this is my first qestion on stackoverflow. I wrote a fuction that expect result from soapClient call in nodejs, but it dont wait for the call return, and the return value is empty.

I try several modification of the code but i cant get the expected result. I expect some output but it is empty.

Note URLS are fictitious!!

Thanks somebody can help me!!


import * as soap from "soap";

function getTokens(service: string): String {

    let Auth = "";

    function Call(err: any, client: soap.Client) {

        client.loginCms({ in0: service }, function (
            err: any,
            result: any,
            _rawResponse: string, 
            _soapHeader: any,
            _rawRequest: string
        ) {
            if (err) {
                console.error(err);
             } else {
                Auth = result.loginCmsReturn;
             }
         });
    }

    soap.createClient("wsdl_url", {
        disableCache: true,
        envelopeKey: "env"
    }, Call, "endpoint_url");

    // here return an empty value
    return Auth;
};

const Auth = getTokens("service");
console.log(Auth); // empty


Solution

  • I recommend you to use promises like in this example taken from the soap package documentation.

    The code you have the is not asynchronic, so it doesn't wait for the operation to be completed.

    It should look something like this

    import * as soap from "soap";
    
    function getTokens(service: string): Promise<string> {
    
        return new Promise<string>((resolve, reject) => {
    
            function Call(err: any, client: soap.Client) {
    
                client.loginCms({ in0: service }, function (
                    err: any,
                    result: any,
                    _rawResponse: string, 
                    _soapHeader: any,
                    _rawRequest: string
                ) {
                    if (err) {
                        console.error(err);
                        reject(err)
                     } else {
                        Auth = result.loginCmsReturn;
                        resolve(Auth);
                     }
                 });
            }
    
            soap.createClient("wsdl_url", {
                disableCache: true,
                envelopeKey: "env"
            }, Call, "endpoint_url");
    
        });
    };
    
    getTokens("service").then((Auth) => {
        console.log(Auth);
    });
    

    Also note that: