Alain
Alain

Reputation: 1470

Is it possible to create my own async Javascript code

I wish to validate my assumptions:

As I read yet, to create an async call, I must eventually end up calling a javascript native call (like setTimeout() || XMLHttpRequest() || ...) to get out of the engine main scheduler loop.

Any third party library wishing to be async, will indirectly do the same.

Is this right, or is there a way to create my own async code (for instance by allowing a blocking feature on my code) intentionally without a js native call ?

Upvotes: 2

Views: 912

Answers (1)

Don Rhummy
Don Rhummy

Reputation: 25820

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"
});

Upvotes: 2

Related Questions