Home Does using promises in node.js make node synchronous?
Reply: 1

Does using promises in node.js make node synchronous?

sdfdsf sdf
sdfdsf sdf Published in 2017-12-07 09:04:10Z

How does promises still retain async while giving sync effect?

I.e Promises can make sequential code execution, doesn’t that remove async?

Then, whats the point of node.js?

Benjamin Gruenbaum
Benjamin Gruenbaum Reply to 2017-12-07 09:09:35Z

No, promises do not make Node.js code run synchronous - promises allow you to write flows that appear synchronous.

When you do this:

setTimeout(() => console.log(2));

Node.js runs the code sequantially, first it logs 1, then it registers a function to happen after a timeout, then it logs 3. After a big when the timer fires - it executes its function and logs 2. No threads are involved.

With promises and async await, when you await you're explicitly telling Node.js "pause executing this function and continue when the promise I'm waiting for resolved". pause executing isn't the same as a thread blocking - no context switch happens at an operating system level - it just keeps track of the function and when the promise resolves it calls it.

Node is run with "our code - platform code" cycles, your code runs (until it ends, for example by hitting an await), then the platform code runs (for example, checking timers and I/O) and then that code can call your code (for example your suspended async function) again and run it.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.329496 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO