How to Create an Asynchronous Function in JavaScript

How can I create an Asynchronous function in Javascript?

You cannot make a truly custom asynchronous function. You'll eventually have to leverage on a technology provided natively, such as:

  • setInterval
  • setTimeout
  • requestAnimationFrame
  • XMLHttpRequest
  • WebSocket
  • Worker
  • Some HTML5 APIs such as the File API, Web Database API
  • Technologies that support onload
  • ... many others

In fact, for the animation jQuery uses setInterval.

Writing custom, true Asynchronous functions in Javascript/Node

Just a side note, true asynchronous doesn't really mean anything. But we can assume you mean parallelism?.

Now depending on what your doing, you might find there is little to no benefit in using threads in node. Take for example: nodes file system, as long as you don't use the sync versions, it's going to automatically run multiple requests in parallel, because node is just going to pass these requests to worker threads.

It's the reason when people say Node is single threaded, it's actually incorrect, it's just the JS engine that is. You can even prove this by looking at the number of threads a nodeJs process takes using your process monitor of choice.

So then you might ask, so why do we have worker threads in node?. Well the V8 JS engine that node uses is pretty fast these days, so lets say you wanted to calculate PI to a million digits using JS, you could do this in the main thread without blocking. But it would be a shame not to use those extra CPU cores that modern PC's have and keep the main thread doing other things while PI is been calculated inside another thread.

So what about File IO in node, would this benefit been in a worker thread?.. Well this depends on what you do with the result of the file-io, if you was just reading and then writing blocks of data, then no there would be no benefit, but if say you was reading a file and then doing some heavy calculations on these files with Javascript (eg. some custom image compression etc), then again a worker thread would help.

So in a nutshell, worker threads are great when you need to use Javascript for some heavy calculations, using them for just simple IO may in fact slow things down, due to IPC overheads.

You don't mention in your question what your trying to run in parallel, so it's hard to say if doing so would be of benefit.

Is it possible to create my own async Javascript code

In JavaScript, there are a few ways to write code that can be run asynchronously. Typically the methods used were:

  1. setTimeout
  2. setInterval
  3. XMLHttpRequest

But in HTML5 (and beyond) there are a lot of other methods that work asynchronously. For example, the new asynchronous file uploading, Web Workers and Promises. (NOTE: not all of these are supported by every browser)

Your question, though, is vague. What are you attempting to do? If it's UI-centric, you may want to look at requestAnimationFrame

If by blocking, you mean you want to show a "loading" gif and then go do stuff and change that after the "stuff" is done, there are a lot of ways to handle that but with the newer browsers, you'd use Promises: http://www.html5rocks.com/en/tutorials/es6/promises/ with a check for some value in a timeout function.

//The value to check
var isDone = false;

var asynchCheck = function(resolve, reject) {

if ( notStarted )
{
// do stuff (calls async function that eventually sets "isDone" = true)
}

if ( isDone === true )
{
if ( no errors ) resolve("Stuff worked!");
else reject(Error("It broke"));
}

//Check again
else setTimeout( asynchCheck, 50 );
}
//Start your function
var promise = new Promise(asynchCheck);

//Now set the success/fail functions
promise.then(function(result) {
console.log(result); // "Stuff worked!"
}, function(err) {
console.log(err); // Error: "It broke"
});

Asynchronous Javascript Confusion

The key thing to understand is that async functions are syntactic sugar for using promises. Neither async functions nor promises make anything happen in the background. They let you wait for and react to things that already happen in the background (like a timer or an HTTP operation completing).

An async function is synchronous up until the first await or return. (That's so it can start whatever asynchronous process it then waits for.) At that point, it returns a promise that will be fulfilled or rejected depending on what happens to the promise being awaited and/or what you return.

await pauses the logic of the function until/unless the promise being awaited settles. (If you use await value where value isn't a thenable [a promise-like thing], you're effectively doing await Promise.resolve(value).)

You haven't shown any contents of the asyncFuncX functions, but unless they await something, they're fully synchronous.

You may find my answer from a couple of days ago useful as well.

How to create custom asynchronous function in Javascript?

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.



Related Topics



Leave a reply



Submit