簡體   English   中英

NodeJS NPM soap - 如何在沒有回調的情況下鏈接異步方法(即使用異步或承諾)?

[英]NodeJS NPM soap - how do I chain async methods without callbacks (ie use async or Promise)?

我已經使用 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文檔中的示例):

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

為了保持承諾鏈平坦,您可以將 soap 的實例分配給外部作用域中的變量:

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);
      });
  })

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM