J. Doe
J. Doe

Reputation: 867

Why is it a best practice to use Asynchornus functions everywhere in nodejs

ive found out that its a best practice for nodeJS / ExpressJS as an API-Endpoint for a ReactJS Software to only use asynchornus functions for mysql-querys etc.

But i really dont get how this should work and why it decrease performance if i didnt use it.

Please imagine the following code:

API Endpoint "/user/get/1" Fetches every datas from user with id one and responds with a json content. If i use async there is no possibility to respond with the information gathered by the query, because its not fulfilled when the function runs to its end.

If i wrap it in a Promise, and wait until its finished its the same like a synchronus function - isnt it?

Please describe for me whats the difference between waiting for a async function or use sync function directly.

Thanks for your help!

Upvotes: 0

Views: 56

Answers (1)

IceMetalPunk
IceMetalPunk

Reputation: 5556

If i wrap it in a Promise, and wait until its finished its the same like a synchronus function - isnt it?

No, it isn't. The difference between synchronous and async functions in JavaScript is precisely that async code is scheduled to run whenever it can instead of immediately, right now. In other words, if you use sync code, your entire Node application will stop everything to grab your data from the database and won't do anything else until it's done. If you use a Promise and async code, instead, while your response won't come until it's done, the rest of the Node app will still continue running while the async code is getting the data, allowing other connections and requests to be made in the meantime.

Using async here isn't about making the one response come faster; it's about allowing other requests to be handled while waiting for that one response.

Upvotes: 2

Related Questions