value from promise is not being exported to another module

北城以北 提交于 2019-12-13 10:30:38

问题


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;

回答1:


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


来源:https://stackoverflow.com/questions/47959024/value-from-promise-is-not-being-exported-to-another-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!