Hi, i am a beginner in node and i wanted to build a cube timer as my first project. Everything worked perfectly until I started doing some calculations on the server. Because of node being asynchronous my code doesn't work and i have totally no idea how to fix it :( Someone told me that i have to use a promise, but i don't really know how to apply it in my case.function sumOfSeconds(fun){ Time.find({}, function(err, data){ if(err) throw err; sumOfSolves = []; for(var i = 0; i < data.length; i++){ sum = data[i].min * 60 + data[i].sec; sumOfSolves.push(sum); } fun(); }) } function best(){ var best = Math.min(...sumOfSolves); var position = sumOfSolves.indexOf(best); Time.find({}, function(err, data){ if(err) throw err; if(data.length === 0){ var bestTime = '-'; }else{ var bestTime = data[position].time; } return bestTime; }) } module.exports = function(app){ app.get('/', function(req, res){ var bestTime = sumOfSeconds(best); Time.find({}, function(err, data){ if(err) throw err; res.render('index', {times: data, bestSolve: bestTime}); }) }); As you probably see in the above the problem is when i request '/' because res.render runs before i have var bestTime defined. How can i approach it? Please take the fact that I am not very advanced in js into consideration. Thanks for your help!!!
Submitted May 29, 2018 at 01:23PM by everek123
No comments:
Post a Comment