Search code examples
javascriptnode.jsecmascript-6es6-promise

value from promise is not being exported to another module


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;

Solution

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