claOnline
claOnline

Reputation: 1045

How Does All Console Logs Get Executed First In Node.js?

I understand that Node.js is asynchronous and uses the event loop to perform I/O tasks. I understand that your code will be parsed first from top to bottom and then later execute user defined callbacks if there are any.

To my understanding writing to the console is also a form of I/O operation (Maybe I'm wrong for thinking is it also an I/O task. Explanation needed if I'm wrong)

So what I don't get is that how/why does all console logs get executed first no matter the position in the script since it is also a form of I/O task?

Upvotes: 2

Views: 933

Answers (2)

Yogeshwar Singh
Yogeshwar Singh

Reputation: 1425

Yes, console.log is also a form of I/O operation and you can take a look at this answer for more details.

Upvotes: 1

nilsonjr
nilsonjr

Reputation: 66

It is fact, the functions in NodeJs and JavaScript is synchronous, however, you can change your function to asynchronous. Below I quoted the example.

1. resetPassword: async function (req, res, next) {
2.    let user = await userService.resetPassword(res.body.email);
3.    console.log(user);
4. }

In this above example, I created the function based on asynchronous and in line 2 will wait to process until response.

Finally, line 3 will print some information about user.

Upvotes: 1

Related Questions