【问题标题】:Using result of one function as a variable in another - node.js使用一个函数的结果作为另一个函数的变量 - node.js
【发布时间】:2018-02-08 17:01:12
【问题描述】:

我正在编写一个 node.js 脚本来生成一个 GitHub 安装访问令牌。这是我得到的:

const axios = require("axios");
var fs = require('fs');
var jwt = require("jsonwebtoken");

var gitInstallationAccessToken = {
  genJWTToken: function(callback) {
    var private_key = fs.readFileSync("/path/to/my/pemfile.pem");

  const now = Math.round(Date.now() / 1000);
  const payload = {
    iat : now,
    exp : now + (10 * 60),
    iss : 7233
  };

  const token = jwt.sign(payload, private_key, { algorithm: 'RS256' })
  callback(token);
  },

  genInstallationAccessToken: function(token, callback) {
    var jwt = gitInstallationAccessToken.genJWTToken(function(token) {
      return token;
    });
    console.log("JWT: ", jwt)
    var instance = axios({
      method: "post",
      url: "https://api.github.com/installations/:installation_id/access_tokens",
      headers: {
        "Accept" : "application/vnd.github.machine-man-preview+json",
        "Authorization" : `Bearer ${jwt}`
      }
    })
    .then(function(response) {
      console.log("Response: ",response.data);
      callback(response);
    })
    .catch(function(error) {
      console.warn("Unable to authenticate");
      // The request was made and the server responded with a status code
      // that falls out of the range of 2xx
      if (error.response) {
        console.warn(`Status ${error.response.status}`);
        console.warn(`${error.response.data.message}`);
      }
    });
  }
}

module.exports = gitInstallationAccessToken;

gitInstallationAccessToken.genInstallationAccessToken(function(response) {
  console.log("response: ", response)
});

我的 JWT 令牌是由 genJWTToken 生成的。我可以看到,如果我在genJWTToken 的回调之前添加console.log("Token: ", token)

我现在需要在genInstallationAccessToken 中使用该令牌,但显然我说错了。如下返回未定义:

var jwt = gitInstallationAccessToken.genJWTToken(function(token) {
  return token;
});
console.log("JWT: ", jwt)

我该如何解决这个问题?

【问题讨论】:

    标签: javascript node.js function jwt


    【解决方案1】:

    我认为你应该考虑重构它并使用链式 Promise,它会更容易理解和控制..

    类似这样的:

    function getToken() {
      return new Promise(function(resolve, reject) {
      	 resolve('token')
      })
    }
    
    
    function chainPromise() {
    	var token
      getToken().then((response) => {
      	token = response
        console.log(token)
      }).then(() => {
      	console.log('I am here and also see: ', token)
      })
    }
    
    chainPromise()

    然后您应该能够很容易地追踪令牌的路径

    【讨论】:

    • 谢谢,我必须阅读一些内容才能理解 Promise,但现在已经整理好了。
    猜你喜欢
    • 1970-01-01
    • 2018-06-30
    • 1970-01-01
    • 1970-01-01
    • 2013-04-22
    • 1970-01-01
    • 2018-01-09
    • 2022-01-26
    • 2023-03-31
    相关资源
    最近更新 更多