Youssef Mohamed
Youssef Mohamed

Reputation: 189

How to create custom asynchronous function in Javascript?

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 ?

Upvotes: 1

Views: 96

Answers (2)

Quentin
Quentin

Reputation: 943569

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.

Upvotes: 0

Bergi
Bergi

Reputation: 664538

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.

Upvotes: 2

Related Questions