nodejs npm soap-如何无回调链异步方法(即使用异步或诺言)



我使用nodejs/javaScript成功地称为SOAP WebService方法的序列,但是使用回调...现在看起来像这样:

soap.createClient(wsdlUrl, function (err, soapClient) {
    console.log("soap.createClient();");
    if (err) {
        console.log("error", err);
    }
    soapClient.method1(soaprequest1, function (err, result, raw, headers) {
        if (err) {
            console.log("Security_Authenticate error", err);
        }
        soapClient.method2(soaprequest2, function (err, result, raw, headers) {
                if (err) {
                    console.log("Air_MultiAvailability error", err);
                }
                //etc... 
        });
    });
});

我正在尝试使用Promise或Async获得更清洁的东西,类似于此(基于此处的文档中的示例https://www.npmjs.com/package/soap/soap(:

var soap = require('soap');
soap.createClientAsync(wsdlURL)
    .then((client) => {
        return client.method1(soaprequest1);
    })
    .then((response) => {
        return client.method2(soaprequest2);
    });//... etc

我的问题是,在后一个示例中,肥皂客户端在第一个调用后不再可访问,并且通常返回"未定义"错误...

是否有一种"干净"的方式可以通过这种链接在随后的呼叫中使用/可访问?

使用async/await语法。

const soap = require('soap');
(async () => {
const client = await soap.createClientAsync(wsdlURL);
cosnt response = await client.method1Async(soaprequest1);
await method2(soaprequest2);
})();

请注意createClientmethod1

上的Async

为了保持承诺链,您可以将肥皂的实例分配给外部范围中的变量:

let client = null;
soap.createClientAsync(wsdlURL)
  .then((instance) => {
    client = instance
  })
  .then(() => {
    return client.method1(soaprequest2);
  })
  .then((response) => {
    return client.method2(soaprequest2);
  });

解决客户端后,将是嵌套链方法调用:

soap.createClientAsync(wsdlURL)
  .then((client) => {
    Promise.resolve()
      .then(() => {
        return client.method1(soaprequest2);
      })
      .then((response) => {
        return client.method2(soaprequest2);
      });
  })

最新更新