首页 > 解决方案 > 如何修复 Node.js/Express 中的竞争条件。我的控制台将正确更新但我的网页没有更新

问题描述

我正在尝试基于几个 API 构建一个简单的网页。我遇到的问题是我的一些 API 在我的页面加载之前没有完成获取他们的数据。目前我的代码如下所示:

app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine', 'ejs')


app.get('/', function (req, res) {
  res.render('index', {weather: null, headlocation: null, lat: null, long: null, imgLinks: null, WebLinks: null, imgLinksFl: null, restLat: null, restLong: null, error: null});

})


// Main Page
app.post('/', function (req, res) {

  city = req.body.city;
  weatherSearch();
  googleStuff();
  filckrSearch();
  zomatoStart();
  res.render('index', {weather: weatherText, headlocation: headLocationText, lat: latLocation, long: longLocation, imgLinks: imageLinks, WebLinks: websiteLinks, imgLinksFl: imageLinksFlick, restLat: latitudeRest, restLong: longitudeRest, error: null});

});

我希望我的页面在收集完所有数据后呈现。例如,我尝试了简单的代码(只是一个伪代码示例):

var flickrdone = ''; 
if (flickrdone = 'done'){
res.render.......
}

但即使我实现了这样的事情,我的页面也被卡住了,什么也没有发生。我是 node/express 的新手,还没有完全理解 app.post 但无论我读了多少,我似乎都无法解决问题。我了解我的页面面临竞争条件,因为我的控制台可以在每次搜索时正确更新,但我的页面没有更新。例如,在我第一次搜索时,如果我输入“Sydney”,那么控制台将使用“Sydney”的正确结果进行更新,但页面不会更新。如果我随后对“珀斯”进行第二次搜索,那么控制台将使用“珀斯”的正确结果进行更新,但页面不会更新。在第三次搜索中,如果输入“布里斯班”,那么控制台将使用来自“布里斯班”的正确结果进行更新 然后页面最终更新为第一次搜索“悉尼”的结果。有人可以解释发生了什么问题并建议如何解决吗?

标签: javascripthtmlnode.jsexpressejs

解决方案


推荐阅读