我有一个NodeJS应用程序,我想我在从嵌套的Promise内部返回时遇到了问题。
如下所示,getToken
函数正在工作。它调用另一个函数来检索密码。在此之后,它在进行GET调用时使用密码值。
然后,我们成功地获得了一个令牌,并将body
打印到控制台。这是可行的。
但是,我现在面临的挑战是将我的令牌body
的值传递给另一个方法以供以后使用。printBodyValue
当前失败,失败时出现“undefined”错误。
如何将值从getToken
内部传递到printBodyValue
getToken: function() {
module.exports.readCredentialPassword()
.then(result => {
var request = require('request-promise');
var passwd = result;
var basicAuthData = "Basic " + (new Buffer("fooUser" + ":" + passwd).toString("base64"));
var options = {
method: "GET",
uri: ("http://localhost:8001/service/verify"),
followRedirects: true,
headers: {
"Authorization": basicAuthData
}
};
return request(options)
.then(function (body) {
console.log("Token value is: ", body);
return body;
})
.catch(function (err) {
console.log("Oops! ", err);
});
});
}
printBodyValue: function() {
module.exports.getToken().then(function(body) {
console.log("Token value from printBodyValue is: \n", body);
});
}
发布于 2018-04-18 01:52:16
在getToken
中,不使用嵌套的promise反模式,而是链接您的promise,并返回最终的promise,这样您就可以使用promise并使用它的解析值:
(另外,由于您使用的是ES6,因此优先使用const
而不是var
)
getToken: function() {
return module.exports.readCredentialPassword()
.then(result => {
const request = require('request-promise');
const passwd = result;
const basicAuthData = "Basic " + (new Buffer("fooUser" + ":" + passwd).toString("base64"));
module.exports.log("Sending Request: ", jenkinsCrumbURL);
const options = {
method: "GET",
uri: ("http://localhost:8001/service/verify"),
followRedirects: true,
headers: {
"Authorization": basicAuthData
}
};
return request(options);
})
.then(function(body) {
console.log("Token value is: ", body);
// the return value below
// will be the final result of the resolution of
// `module.exports.readCredentialPassword`, barring errors:
return body;
})
.catch(function(err) {
console.log("Oops! ", err);
});
}
printBodyValue: function() {
module.exports.getToken().then(function(body) {
console.log("Token value from printBodyValue is: \n", body);
});
}
https://stackoverflow.com/questions/49889916
复制