0

Some methods of modules in nodejs use callback(asynchronous) and some use return(synchronous). When is the best time to use either? What are the things you should consider? and What are the performance impacts?

Gene Diaz
  • 536
  • 1
  • 7
  • 22

2 Answers2

1

Generally, you don't have a choice as a node.js developer. If your function only uses synchronous library functions, it can be synchronous and return a value. If your function uses any asynchronous API from either node core or a supporting library, your function must also be asynchronous and use a callback. The general rule is any IO (disk, network, process) requires a callback. The exception to the rule is when you are writing a utility script such as a build script or single-user command line program (as opposed to a network service), in which case you can use the synchronous APIs from node core.

was asynchronous used due to performance?

In node.js itself, the choice of asychronous IO, single thread, and a single event loop was made for 2 major reasons: performance (mostly around efficiency when handling many connections) and programming style (mostly with the idea that writing correct multithreaded code is more difficult than writing correct event-based async code).

But in your day to day coding, node.js is primarily useful in writing network servers and in network servers using any synchronous IO will degrade performance severely (synchronous IO in a node.js network server is violating the main principle that makes node.js work), so the way I think of it is all IO is asynchronous and it is only OK to do synchronous IO under a very small whitelist of specific circumstances such as when you program is initially starting and loading (require('foo') is synchronous) or you are writing an command line program that does not provide a network service (build scripts, utilities, etc).

Peter Lyons
  • 142,938
  • 30
  • 279
  • 274
0

Not exactly same question but answer to your question is hidden behind this question too. Javascript acts like all other programming languages and executes sequentially, except when it waits for other service to give it a response. Instead of waiting for response from other services and blocking next instructions, it executes following instructions. This design is called asynchromous. When you are using any asynchronous call use callback. Otherwise you can use return. Here are some scenarios of both synchronous and asynchronous behavior.

Community
  • 1
  • 1
taufique
  • 2,701
  • 1
  • 26
  • 40