来自promise的值未导出到另一个模块 [英] value from promise is not being exported to another module

查看:144
本文介绍了来自promise的值未导出到另一个模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

https://jsfiddle.net/oc5v4bs5/ < ==链接到代码

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

在导出accToken变量时,它显示未定义的值.为什么显示?

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;

推荐答案

您正在导出accToken,然后设置其值. oauth2.getOAuthAccessToken()是异步的.这意味着它完成并在将来的某个模块初始化完成之后以及您的module.exports = accToken;语句执行之后的某个时候调用其回调.因此,当您的export语句运行时,尚未设置accToken.

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.

您将需要导出promise,并让调用方在promise上使用.then()以获取价值.只有在诺言得以解决时,价值才可用.或者,您可以导出一个返回诺言的方法,让调用方根据需要对其进行调用,并且仍然对返回的诺言使用.then()来访问该值.

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

然后,在哪里使用它:

require('./token.js').then(token => {
    // use token here
});

这篇关于来自promise的值未导出到另一个模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆