Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

https://jsfiddle.net/oc5v4bs5/ <==link to the code

when exporting accToken variable, it is showing undefined value. why is this showing?

//core modules
const OAuth2 = require('oauth').OAuth2;

//vars
const clientId = '<myClientId>';
const clientSecret = '<myClientSecret>';
let accToken;
const oauth2 = new OAuth2(
  clientId,
  clientSecret,
  'https://accounts.spotify.com/',
  null,
  'api/token',
  null);
//make gotAuth promise
const gotAuth = 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);
      }
   });
});
gotAuth.then((val)=>{
  accToken = val;
});
module.exports = accToken;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
312 views
Welcome To Ask or Share your Answers For Others

1 Answer

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
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...