You are exporting accToken
BEFORE its value has been set. oauth2.getOAuthAccessToken()
is asynchronous. That means it finishes and calls its callback sometime in the future after your module initialization has already finished and after your module.exports = accToken;
statement executes. So, accToken
has not yet been set when your exports statement runs.
You will need to export the promise and let the caller use .then()
on the promise to get the value. Only when the promise resolves is the value available. Or, you can export a method that returns a promise and let the caller call it upon demand and still use .then()
on the returned promise to get access to the value.
module.exports = new Promise((resolve,reject)=>{
oauth2.getOAuthAccessToken('',{'grant_type':'client_credentials'},
(err, access_token, refresh_token,results)=>{
if(access_token){
resolve(access_token);
}else if(err){
reject(err);
}
});
});
Then, where you use it:
require('./token.js').then(token => {
// use token here
});
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…