0

My question is regarding a very basic concept of JS. To understand the beauty of Promise and Async-Await I created a normal code first which executes line by line.

I've been taught that in traditional code, if one line is busy with some process for few seconds then remaining lines of code will have to wait. My understanding is this:

line of code 1 // completed
line of code 2 // completed
server interaction  // waiting for response from server
line of code 3 // waiting
line of code 4 // waiting
line of code 5 // waiting

To mimic this server delay I used setTimeout(3000) but still I can see rest of the lines are being executed normally. Here's my code:

ngOnInt() {
  console.log("hello");
  console.log("how");
  setTimeout(()=>{
    console.log("i was waiting");
  }, 3000);
  console.log("are");
  console.log("you");
}

Output:

hello
how
are
you
i was waiting
 

I was expecting that "hello", "how" will get printed first, then after 3 seconds "are", "you" will be printed. Where I am making mistake. Please correct me.

Tanzeel
  • 4,174
  • 13
  • 57
  • 110
  • `setTimeout` means "Run this function after this time". It **doesn't** mean, that and "stop doing absolutely everything else while you wait". – Quentin Jun 26 '21 at 09:32
  • 1
    `setTimeout` **doesn't** delay the main execution thread. It schedules a function to be called back *later*, asynchronously, after (roughly) the specified number of milliseconds if the thread isn't busy doing something else. To do what you wanted to do, you could use a busy wait, which **normally you don't want to do**: `let stop = Date.now() + 3000; while (Date.now() < stop) { /*...do nothing...*/ }` (Again, that would be bad practice in the normal case.) – T.J. Crowder Jun 26 '21 at 09:34
  • @T.J.Crowder, I understand what you said :-) But i want to create the problem explicitly to see how Promise and Async-Await have resolved it later – Tanzeel Jun 26 '21 at 09:36
  • console.log("hello"); console.log("how"); await new Promise((resolve,reject)=>{ setTimeout(()=>{ resolve( console.log("i was waiting")); }, 3000);}) console.log("are"); console.log("you"); – Toufiq Ahmed Jun 26 '21 at 09:36
  • @Tanzeel - Right, exactly, that's why I showed you how to do it. I just meant, don't do it *otherwise*. :-) Side note: I go into promises and `async`/`await` in depth in Chapters 8 and 9 of my recent book *JavaScript: The New Toys*. Links in my profile if you're interested. – T.J. Crowder Jun 26 '21 at 09:38
  • @T.J.Crowder, of course I'm interested. thanks for sharing. – Tanzeel Jun 26 '21 at 09:40
  • @T.J.Crowder, You can add it as an answer so that we can close this question. – Tanzeel Jun 26 '21 at 09:41
  • @Tanzeel - The question is already closed. :-) I can't post an answer to a closed question. See the linked question's answers for more. Happy coding! – T.J. Crowder Jun 26 '21 at 09:41

0 Answers0