[英]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); })();
注意createClient
和method1
上的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.