Node.js中fetch异步操作导致myGlobalData未定义的原因咨询
为什么全局变量
myGlobalData始终为undefined,而局部变量myLocalData能正常打印? 嘿,这个问题我太熟了——本质上是异步JavaScript的执行顺序在搞鬼!咱们拆解一下你的代码逻辑,就能明白为啥会这样:
问题核心:异步操作的执行时机
fetch()是一个异步网络请求:它不会卡住后续代码的执行,Node.js会先去处理这个请求,同时继续往下跑同步代码。then()里的回调是异步触发的:只有当fetch请求成功拿到响应后,then里的赋值和打印操作才会执行。- 你在
then外面直接打印myGlobalData:这行代码是同步执行的——它会在fetch请求还没完成、then回调还没跑的时候就执行了,这时候myGlobalData根本还没被赋值,自然就是undefined。
而myLocalData是在then回调里打印的,这时候请求已经完成、赋值操作也执行了,所以能正常输出内容。
解决方案1:把依赖myGlobalData的逻辑放进then回调里
既然myGlobalData的赋值是异步完成的,所有需要用它的代码都得等异步操作结束,最简单的方式就是把后续逻辑写在then里面:
app.post('/thank', urlencodedParser, function (req, res){ var reply=''; var mydata = fetch('https://facebook.github.io/react-native/movies.json'); mydata.then(function(response) { return response.text() }).then(function(text) { myGlobalData = text; myLocalData = text; console.log(myLocalData); // 所有需要用myGlobalData的逻辑都放这里 console.log(myGlobalData); // 这里就能正常打印了 res.send(`<p>获取到的数据:${myGlobalData}</p>`); }); });
解决方案2:用async/await简化异步代码
async/await能让异步代码看起来像同步代码,可读性更高,也能避免回调嵌套:
app.post('/thank', urlencodedParser, async function (req, res){ // 给回调加async关键字 var reply=''; try { const response = await fetch('https://facebook.github.io/react-native/movies.json'); // await等待请求完成 const text = await response.text(); myGlobalData = text; console.log(myLocalData); console.log(myGlobalData); // 这里也能正常打印 res.send(`<p>获取到的数据:${myGlobalData}</p>`); } catch (error) { // 处理请求失败的情况 console.error('请求出错:', error); res.send('获取数据失败,请重试'); } });
小提醒
全局变量myGlobalData在多请求场景下容易引发竞态问题(比如多个请求同时修改它),如果不是必须,更推荐把数据放在请求上下文里,或者用局部变量结合异步逻辑处理。
你的原始代码参考:
var fetch = require("node-fetch"); var http = require("http"); var express = require('express'); var app = express(); var bodyParser = require('body-parser'); var urlencodedParser = bodyParser.urlencoded({ extended: true }); let myGlobalData; // Running Server Details. var server = app.listen(8082, function () { var host = server.address().address var port = server.address().port console.log("Example app listening at %s:%s Port", host, port) }); app.get('/form', function (req, res) { var html=''; html +="<body>"; html += "<form action='/thank' method='post' name='form1'>"; html += "web URL:</p><input type='text' name='weburl'>"; html += "<input type='submit' value='submit'>"; html += "<INPUT type='reset' value='reset'>"; html += "</form>"; html += "</body>"; res.send(html); }); app.post('/thank', urlencodedParser, function (req, res){ var reply=''; var mydata = fetch('https://facebook.github.io/react-native/movies.json'); mydata.then(function(response) { return response.text() }).then(function(text) { // var myLocalData = text; myGlobalData = text; myLocalData = text; console.log(myLocalData); }); console.log(myGlobalData); // result is undefined Why? });
内容的提问来源于stack exchange,提问作者joe the coder
相关产品推荐
相关产品推荐

