Introduction to Node.js Asynchronous Code in Node.js
This course has been updated! We now recommend you take the Introduction to Node.js, v2 course.
Transcript from the "Asynchronous Code in Node.js" Lesson
[00:00:20] But I'm just gonna talk about it for a little bit. So if you've ever used any other language like Ruby, or Python, or anything like that, right, it's multi-threaded, right? So you have many threads on your machine, and let's say you have a server in Python, every request that comes in is gonna be its own thread, right?
[00:00:54] But it enables one thing but it the kind of sucks the life out of something else. So it enables high concurrency, because of that, you can register many things to do at once basically. So because it's asynchronous and you can do things in the background, you can have many operations coming in like, okay, okay.
[00:01:10] You want me to do this, you want me to do this, you want me to do this, you want me to do this, and it will just like cool. I'm going to do all this and continue to go to the next line, while it's doing other stuff in the background, right?
[00:01:54] If you ever did a set timeout, you used async code. If you ever did any Listener or any DOM element ever, that was async code. It's the same in Node. The only difference is, and we'll get to it in a little more detail, but it's how your app is being used, right?
[00:02:31] So it's a little different, so now you actually have to consider asynchronous code because it could affect your app. It could kill it, it could cause problems you were not aware of. Yeah, so, node.js is single threaded and event-based, just like the browser. Like I said, unlike the browser, your node.js app will be shared by all clients.
[00:02:51] And this is mostly true for APIs. Even then, at the end of the day you still have one machine that's gonna be handling many requests. And if you have one piece of code that's blocking, like reading a file synchronously, then every request has to wait for that to be done.
[00:03:05] It can't do anything else. It can't register a new task cuz it's waiting on this infinite while loop that you created, that's never-ending. So this is why asynchronous code is very important to Node, because without it kind of fails. Okay, so again you have to consider CPU-intensive tasks that block a single thread, so while loops.