Node.js中如何将fetch获取的JSON数据存储到外部作用域变量
问题原因分析
showObj无输出:你从未给全局声明的mainObj对象赋值,遍历空对象自然没有任何打印内容。- 全局
theblockPrices无法拿到值:你在fetch的then回调中用let theblockPrices重新声明了局部变量,该变量和顶部声明的全局theblockPrices是完全独立的两个变量,赋值仅作用于局部变量,全局变量一直保持初始空数组。 - 核心异步逻辑问题:
fetch是异步API,发起请求后代码会继续向下执行,不会等待请求返回,因此无法像同步代码一样在fetch调用后直接读取返回数据。
解决方案
方案1:基于Promise回调写法(兼容旧版本)
修正现有代码的变量赋值问题,所有依赖返回数据的逻辑都在请求完成的回调中执行:
let theSystem, themaxPrice, theblockPrices = [], mainObj = {}; let showObj = function() { for (let prop in mainObj) { console.log(prop); console.log(mainObj[prop]); } }; // 业务逻辑函数 function totalAmntEarned(thePrice, theAmntSold) { return thePrice * theAmntSold; } fetch(URL, { method: 'GET', headers: { Authorization: AUTH_KEY } }) .then(function(resp) { return resp.json(); }) .then(function(data) { // 直接给全局变量赋值,不要加let重新声明 mainObj = data; themaxPrice = data.maxPrice; theblockPrices = data.blockPrices; // 赋值完成后再调用依赖这些变量的函数 showObj(); console.log(themaxPrice); console.log(theblockPrices[0]); // 调用其他业务函数 const totalEarned = totalAmntEarned(themaxPrice, theblockPrices.length); console.log(totalEarned); });
方案2:async/await写法(更易读,推荐)
Node.js环境下推荐用async/await语法,书写体验和同步代码几乎一致,更符合你预期的调用逻辑:
// 业务逻辑函数 function totalAmntEarned(thePrice, theAmntSold) { return thePrice * theAmntSold; } // 所有逻辑放在async函数内 async function main() { // 等待请求完成再执行后续逻辑 const resp = await fetch(URL, { method: 'GET', headers: { Authorization: AUTH_KEY } }); const data = await resp.json(); // 后续代码可直接使用data,和同步写法体验一致 const thePrice = data.price; const theAmntSold = data.soldAmount; const totalEarned = totalAmntEarned(thePrice, theAmntSold); console.log(totalEarned); // 如果需要给其他脚本调用,可将数据挂载到导出对象 module.exports = { theblockPrices: data.blockPrices, maxPrice: data.maxPrice, data } } // 执行主函数 main();
注意事项
所有依赖接口返回数据的逻辑,必须在异步请求完成后执行,不能在fetch调用后直接同步读取变量,此时请求尚未返回,变量仍为初始值。如果其他脚本需要使用该数据,可在其他脚本中引入导出的Promise对象等待数据返回即可。
内容的提问来源于stack exchange,提问作者donnie b
相关产品推荐
相关产品推荐

