1

I am new to JS so please forgive my lack of understanding.

Suppose I work with MongoDB and I want to fetch details from a particular database in an asynchronous manner.

I would love to understand how this happens in JavaScript because the language is defined as a single threaded.

for example to execute this line asynchronously:

myCursor = db.inventory.find( {} )

I have read about the subject a lot and I understand that some asynchronous functions like setTimeOut are executed by Web API'S. Will each asynchronous function be the responsibility of the web APIs?

Many thanks

  • **1st** You don't need to do anything to make it async, And its impossible to block its asynchronous manner. **2nd** The main reason of asynchronous is to use less thread, Even a single thread would do the job! – Nur May 24 '21 at 22:10
  • "*Will each asynchronous function be the responsibility of the web APIs?*" - ultimately, [yes](https://stackoverflow.com/a/61857303/1048572). Though of course in your case it's Node.js APIs, not Web APIs. – Bergi May 24 '21 at 23:07
  • Thanks! @Nur can you elaborate further on 2? Why does asynchronous behavior reduce the amount of threads? – eden gavriel May 25 '21 at 04:48
  • You can use [MongoDB NodeJS Driver](https://docs.mongodb.com/drivers/node/current/) to access the database - the API supports asynchronous JavaScript. – prasad_ May 25 '21 at 07:23

1 Answers1

1

So you asked: "Why does asynchronous behavior reduce the amount of threads?" -

Note: Don't confuse threading with using multicore, Its totally deferent concept , But of course thread can take advantage of multicore system, But now Lets think we have a single core CPU.

Threading

A thread of execution is the smallest sequence of programmed instructions that can be managed independently by a scheduler, (Basically small unit of execution).

For I/O operation (like making a network call) take time but program need to wait and wasting valuable computation power by doing nothing, So historically we use thread that execute a task independently,

Its has some drawback, One of is memory concussion (Because Its need to clone register, stack, counter), this is a deferent topic. Also thread are so expensive to switch context...

So we know that thread are expensive, What if we can reduce thread count ?

Asynchronous

The idea is to use Event, and execute via a library ( Also known: runtime, executor etc...), without the program blocking to wait for results.

Its cheep and efficient for I/O intensive tasks. Even, It can use a single thread to do all async stuff!

Nur
  • 2,361
  • 2
  • 16
  • 34