我有一个带有函数(createClient)的对象(SoapClient),它返回一个已解析或被拒绝的promise。承诺的履行价值是客户。我试图调用SoapClient.createClient并在'然后'方法,将已完成的promise值分配给我的本地客户端变量,但除非我返回该函数,否则它不起作用。有人可以解释原因吗?谢谢。这是我的代码:
SoapClient模块:
const soap = require('some soap library').soap;
module.exports = {
createClient: (options) => {
const { option1, option2, option3, option4 } = options;
return new Promise((resolve, reject) => {
if (!option1 || !option2) {
reject('some error message');
}
soap.createClient(option3, {endpoint: option4}, (err, client) => {
if (err) {
reject(err);
}
//some code to set authentication here
resolve(client);
})
});
}
};
一些测试类:
before(() => {
let soapClient;
const options = { option1: 'something', option2: 'something', option3: 'something', option4: 'something' }
return SoapClient.createClient(options)
.then((client) => {
soapClient = client;
})
.catch((err) => {
throw new Error(err);
});
});
在这种情况下,soapClient被正确分配了客户端的履行承诺值,但如果我删除了返回,则soapClient变为未定义。为什么是这样?有没有办法在没有返回的情况下为soapClient分配正确的值?感谢。
答案 0 :(得分:0)
这将返回两个警报:
var SoapClient = {
createClient: function() {
return Promise.resolve(true)
.then(function(x) {
return 'client';
});
},
createClient1: function() {
return Promise.resolve('client');
}
}
SoapClient.createClient()
.then(function(client) {
alert(client);
});
SoapClient.createClient1()
.then(function(client) {
alert(client);
})
答案 1 :(得分:0)
您可以创建return
Promise
值或拒绝原因的函数。在链式.then()
let getClient = (options) => {
const options = Object.assign({ option1: 'something', option2: 'something' }, options);
return SoapClient.createClient(options)
.then(client => client)
.catch((err) => {
throw new Error(err);
});
}
let soapClient = getClient(/* {option1:"abc"} */);
soapClient.then(success, err);