![](/img/trans.png)
[英]How to pass variable from one function to another function in Node.js?
[英]Using result of one function as a variable in another - node.js
我正在编写一个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)
我该如何解决?
我认为您应该考虑对此进行重构,并使用链接的诺言,这样会更易于理解和控制。
像这样:
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()
然后,您应该能够轻松地跟踪令牌的路径
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.