Node.js中用teemojs调用Riot API,如何将返回值存入全局变量?
解决teemojs调用Riot API后无法存入全局变量的问题
Hey Luke, 刚好我之前也踩过类似的异步赋值坑,这就帮你捋清楚怎么解决!
问题根源
你之所以存不到全局变量,核心原因是teemojs的API调用是异步操作——当你尝试在回调函数外直接访问变量时,API请求还没完成,变量自然还是初始值(比如undefined)。举个典型的错误写法例子:
let riotData; // 全局变量 // 调用API teemojs.lol.summoner.getBySummonerName({ summonerName: 'YourSummoner' }) .then(data => { riotData = data; console.log('回调里的data:', data); // 这里能正常拿到数据 }); console.log('全局变量riotData:', riotData); // 这里输出undefined,因为异步还没跑完!
解决方案
下面给你两种最常用的正确写法,按需选择:
1. 使用async/await(推荐,代码更简洁易读)
把API调用逻辑包裹在async函数里,用await等待异步操作完成后再赋值,这样就能确保变量拿到数据后再被使用:
let globalRiotData; // 全局变量 async function fetchRiotData() { try { // 等待API返回数据后再赋值 globalRiotData = await teemojs.lol.summoner.getBySummonerName({ summonerName: 'YourSummoner' }); // 这里可以直接使用globalRiotData,后续需要用的逻辑也可以放在这里或之后 console.log('获取到的数据:', globalRiotData); processData(globalRiotData); // 比如传递给处理函数 } catch (error) { // 别忘了处理API调用可能出现的错误 console.error('获取Riot数据失败:', error); } } // 调用函数触发异步请求 fetchRiotData(); // 注意:如果在fetchRiotData()外面直接打印globalRiotData,依然会是undefined // 必须等fetchRiotData里的await完成后,变量才会有值
如果你的Node.js环境支持顶层await(Node.js 14.8+,或者把文件设为ES模块:后缀.mjs或在package.json里加"type": "module"),还可以更简洁:
let globalRiotData; try { globalRiotData = await teemojs.lol.summoner.getBySummonerName({ summonerName: 'YourSummoner' }); } catch (error) { console.error('获取数据失败:', error); } // 这个模块里后续的代码都能访问到有值的globalRiotData了
2. 使用Promise的.then()链式调用
如果你习惯用Promise的链式写法,确保所有需要使用变量的逻辑都放在.then()回调里,或者通过回调传递:
let globalRiotData; teemojs.lol.summoner.getBySummonerName({ summonerName: 'YourSummoner' }) .then(data => { globalRiotData = data; // 所有依赖这个变量的操作都要放在这里面 console.log(globalRiotData); processData(globalRiotData); }) .catch(error => { console.error('请求失败:', error); });
额外建议:尽量避免全局变量
虽然解决了赋值问题,但全局变量容易引发意外的变量污染或修改。更优雅的做法是:
- 把获取到的数据直接传递给需要它的函数(比如上面例子里的
processData) - 如果是在模块里,把数据导出,让其他模块通过
import访问
内容的提问来源于stack exchange,提问作者Luke Noot
相关产品推荐
相关产品推荐

