How to fix a race condition in Node.js/Express. Where my console will update correctly but my webpage doesn't update

你离开我真会死。 提交于 2019-12-25 01:44:07

问题


I am trying to build a simple webpage based on a couple API's. The issue i am running into is that some of my API's aren't finished getting their data before my page is loaded. Currently my code looks like the following:

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

});

I want my page to render once all the data is collected. i have tried simple code for example (just a pseudocode example):

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

But even when i implement something like this my page is stuck loading and nothing ever happens. I am new to node/express and haven't fully understood app.post but no matter how much i read i can't seem to solve the problem. I understand my page is facing a race condition because my console can update correctly upon each search but my page doesn't update. For example upon my first search if i type 'Sydney' then the console will update with the correct results from 'Sydney' but the page will not update. If i then do a second search of 'Perth' then the console will update with the correct results from 'Perth' but the page will not update. On the third search if type in 'Brisbane' then the console will update with the correct results from 'Brisbane' and then the page finally updates with the results from the first search of 'Sydney'. Can someone please explain what is going wrong and suggest how to fix it?

来源:https://stackoverflow.com/questions/52271829/how-to-fix-a-race-condition-in-node-js-express-where-my-console-will-update-cor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!