0

I know that to create an asynchronous function all we need is to call an asynchronous function inside it like setTimeout() and passing a callback.

But how to create that natively without using any prebuilt function to achieve that ?

I know that functions that query a database have an asynchronous behavior, how do they do that without using something like setTimeout() in their original implementation ?

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Youssef Mohamed
  • 159
  • 2
  • 9
  • 2
    possible duplicate of [How do you create custom asynchronous functions in node.js?](https://stackoverflow.com/q/22286887/1048572) – Bergi May 17 '20 at 19:10
  • 2
    can you elaborate the exact usecase and what do you want to achieve out of that? – Pavan May 17 '20 at 19:12
  • @Bergi I want to understand how to build a code that can be called and doesn't block the rest of the code. (without setTimeout like database queries functions does) – Youssef Mohamed May 17 '20 at 19:28
  • You could do this with Async await – Afaq Ahmed Khan May 17 '20 at 19:29
  • @YoussefMohamed I repeat (from my answer): you cannot do that. I assume that you count the solution "putting the code in a worker process" as "using any prebuilt function". – Bergi May 17 '20 at 19:35

2 Answers2

1

But how to create that natively without using any prebuilt function to achieve that?

You cannot.

I know that functions that query a database have an asynchronous behavior, how do they do that without using something like setTimeout() in their original implementation?

They usually will connect to the database using a network or filesystem socket, and for those there are builtin asynchronous functions (calling a callback when a response is received etc) that they build upon.

For node.js specifically, there is of course also the possibility of writing an addon to the engine itself that supplies such a "natively asynchronous" function to the JavaScript environment.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0

Such functions usually aren't written in JavaScript.

They are usually written in the same programming language as the runtime engine and then plugged into it and exposed as a JavaScript function.

This is why if you were to run XMLHttpRequest.toString() in a browser, you'll get "function XMLHttpRequest() { [native code] }" and not the actual code of the function.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335