Javascript 将嵌套承诺返回给另一个函数

Javascript 将嵌套承诺返回给另一个函数,javascript,node.js,Javascript,Node.js,我有一个NodeJS应用程序,我想我在从嵌套承诺中返回时遇到了问题 如下所示,getToken函数正在工作。它调用另一个函数来检索密码。之后,它在进行GET调用时使用密码值 然后,我们成功地获得一个令牌,并将正文打印到控制台。这很有效 然而,我现在面临的挑战是将body的值传递给另一种方法,以供以后使用printBodyValue当前失败,并出现“未定义”错误 如何将值从内部深处getToken传递到printBodyValue getToken: function() { module.

我有一个NodeJS应用程序,我想我在从嵌套承诺中返回时遇到了问题

如下所示,
getToken
函数正在工作。它调用另一个函数来检索密码。之后,它在进行GET调用时使用密码值

然后,我们成功地获得一个令牌,并将
正文
打印到控制台。这很有效

然而,我现在面临的挑战是将
body
的值传递给另一种方法,以供以后使用<代码>printBodyValue当前失败,并出现“未定义”错误

如何将值从内部深处
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);
   });
}

getToken
中,不要使用嵌套的promise anti模式,而是链接承诺,并返回最终承诺,这样您就可以使用承诺并使用其解析值:

(另外,由于您使用的是ES6,因此更喜欢
const
而不是
var


不要查看代码内部,但如果格式正确,
getToken
不会返回任何内容,
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);
  });
}