0
app.get('/', (req, res)=> {
    var x, y, z;
    setTimeout(() => {
        x = 10
    }, 5000);

    setTimeout(() => {
        y = 20
    }, 3000);


    setTimeout(() => {
        z = x+y
    }, 2000);

    res.send('The sum is'+ z);
})

now the API response is undefined, but if I write the setTimeout() one into another

   setTimeout(()=> {
      setTimeout(()=>{
          ....
      });
   });

Then it works fine. How can I solve that with Promise and Async/Await

Rabbani_
  • 450
  • 1
  • 10
  • 30
  • because your last setTimeout will trigger first and it tries to add x and y which does not have the value at that time, Also the res.send will invoke immediately without waiting for the setTimeouts and will return undefined for the variable z. – Tinu Jos K Jan 28 '20 at 05:41
  • You canuse Promise.all() to resolve all Promises at once. – Tejas Jan 28 '20 at 05:43
  • last setTimeOut is small so it will execute before x and y. so if you want delay then give x and y delay less then z delay so that x and y get initialized – Amit Tiwary Jan 28 '20 at 05:45
  • 1
    Yes I got it @Tick20 && Amit Tiwary – Rabbani_ Jan 28 '20 at 05:47
  • @GeorgeBailey can you please solve this using async/await this answer is too much described and solved on ajax request but I need to implement that with Node api.. – Rabbani_ Jan 28 '20 at 05:52
  • someone solve the problem with async and await please – Rabbani_ Jan 28 '20 at 05:53
  • One more note: Using `setTimeout` doesn't ensure that your code will run in the order you want, even if the timeout's order is OK: `setTimeout` ensures your code won't run bedore the given time, but it may execute later, so to make a failsafe approach, you have to check that the previous timeout has finished. Here is where Promises are handy... – FZs Jan 28 '20 at 05:53

0 Answers0