22

I am trying to grasp on Javascript Asynchronous functions and callbacks.

I got stuck on the concept of callback functions, where I am reading on some places: they are use to have sequential execution of code (mostly in context of jquery e.g animate)and some places specially in the context of Nodejs; they are use to have a parallel execution Asynchronous and avoid blocking of code.

So can some expert in this topic please shed light on this and clear this fuzz in my mind (examples??). so I could make my mind for the usage of callback function

or that is solely depends on the place of where you are calling/placing a callback function in your code? .

Thanks,

P.S: I am scared that this question would be close as subjective but still I could expect concrete answer for this (perhaps some examples)

Edit: actually this is the example from internet which makes me ambigous:

function do_a(){
  // simulate a time consuming function
  setTimeout( function(){
    console.log( '`do_a`: this takes longer than `do_b`' );
  }, 1000 );
}

function do_b(){
  console.log( '`do_b`: this is supposed to come out after `do_a` but it comes out before `do_a`' );
}

do_a();
do_b();

Result

`do_b`: this is supposed to come out after `do_a` but it comes out before `do_a`
`do_a`: this takes longer than `do_b`

when JS is sequential then do_b should always come after do_a according to my understanding.

static void main
  • 728
  • 2
  • 9
  • 34
  • 8
    JavaScript is JavaScript; it's dependent on context, usage, engine, etc. – Dave Newton May 13 '13 at 14:00
  • Can you provide some example code that you're not sure if it is blocking vs nonblocking? – Matt May 13 '13 at 14:06
  • JavaScript is in general synchronous, but setTimeout is asynchronous by definition. Here's a good primer on it: https://developer.mozilla.org/en-US/docs/DOM/window.setTimeout – Colin DeClue May 13 '13 at 14:25

4 Answers4

27

The core of JavaScript is largely synchronous, in that functions complete their task fully, before completing. Prior to the advent of AJAX, it was really only setTimeout and setInterval that provided asynchronous behavior.

However, it's easy to forget that event handlers are, effectively async code. Attaching a handler does not invoke the handler code and that code isn't executed until some unknowable time in the future.

Then came AJAX, with its calls to the server. These calls could be configured to be synchronous, but developers generally preferred async calls and used callback methods to implement them.

Then, we saw the proliferation of JS libraries and toolkits. These strove to homogenize different browsers' implementations of things and built on the callback approach to async code. You also started to see a lot more synchronous callbacks for things like array iteration or CSS query result handling.

Now, we are seeing Deferreds and Promises in the mix. These are objects that represent the value of a long running operation and provide an API for handling that value when it arrives.

NodeJS leans towards an async approach to many things; that much is true. However this is more a design decision on their part, rather than any inherent async nature of JS.

Dancrumb
  • 26,597
  • 10
  • 74
  • 130
14

Javascript is always a synchronous(blocking) single thread language but we can make Javascript act Asynchronous through programming.

Synchronous code:

console.log('a');
console.log('b');

Asynchronous code:

console.log('a');
setTimeout(function() {
    console.log('b');
}, 1000);
setTimeout(function() {
    console.log('c');
}, 1000);
setTimeout(function() {
    console.log('d');
}, 1000);
console.log('e');

This outputs: a e b c d

T3KBAU5
  • 1,861
  • 20
  • 26
Deepak Sisodiya
  • 850
  • 9
  • 11
  • what does blocking mean in this context? – Sandeepan Nath Mar 14 '16 at 18:38
  • 1
    @SandeepanNath You may have already figured it out, but for future visitors: blocking refers to serial processing. Doing one thing at a time. On the other hand, non-blocking code (asynchronous) can run in parallel (or multithreaded). The advantage is that it can be faster. – Connor Jun 28 '19 at 18:09
3

In node long running processes use process.nextTick() to queue up the functions/callbacks. This is usually done in the API of node and unless your programming(outside the api) with something that is blocking or code that is long running then it doesn't really effect you much. The link below should explain it better then I can.

howtonode process.nextTick()

jQuery AJAX also takes callbacks and such as it its coded not to wait for server responses before moving on to the next block of code. It just rememebers the function to run when the server responds. This is based on XMLHTTPRequest object that the browsers expose. The XHR object will remember the function to call back when the response returns.

setTimeout(fn, 0) of javascript will run a function once the call stack is empty (next available free tick) which can be used to create async like features.setTimeout(fn, 0) question on stackoverflow

To summerise the async abilities of javascript is as much to do with the environments they are programmed in as javascript itself. You do not gain any magic by just using lots of function calls and callbacks unless your using some API/script.

Jquery Deferred Object Is another good link for async capabilities of jQuery. Googling might find you information on how jQuery Deferred works also for more insight.

Community
  • 1
  • 1
Adam
  • 1,059
  • 9
  • 15
0

In JavaScript the term "asynchronous" typically refers to code that gets executed when the call stack is empty and the engine picks a job from one of its job queues for execution.

Once code is being executed, it represents a synchronous sequence of execution, which continues until the call stack is empty again. This sequence of execution will not be interrupted by events in order to execute some other JavaScript code (when we discard Web Workers). In other words, a single JavaScript environment has no preemptive concurrency.

While synchronous execution is ongoing, events might be registered as jobs in some job queues, but the engine will not process those before first properly execution what is on the call stack. Only when the call stack is empty will the engine take notice of the job queues, pick one according to priority, and execute it (and that is called asynchronous).

Callbacks

Callbacks can be synchronous or asynchronous -- this really depends on how they are called.

For instance, here the callback is executed synchronously:

new Promise(function (resolve) { /*  .... */ });

And here the callback is executed asynchronously:

setTimeout(function () { /* ... */ });

It really depends on the function that takes the callback as argument; how it deals with eventually calling that callback.

Ways to get code to execute asynchronously

The core ECMAScript language does not offer a lot of ways to do this. The well-known ones are offered via other APIs, such as the Web API, which are not part of the core language (setTimeout, setInterval, requestAnimationFrame, fetch, queueMicrotask, addEventListener, ...).

Core ECMAScript offers Promise.prototype.then and (depending on that) await. The callback passed to then is guaranteed to execute asynchronously. await will ensure that the next statements in the same function will be executed asynchronously: await makes the current function return, and this function's execution context will be restored and resumed by a job.

It also offers listening to when the garbage collector is about to garbage collect an object, with FinalizationRegistry.

Web Workers

Web Workers will execute in a separate execution environment, with their own call stack. Here preemptive concurrency is possible. When the term asynchronous is used in the JavaScript world, it typically does not refer to this kind of parallelism, although the communication with a Web Worker happens via asynchronous callback functions.

trincot
  • 317,000
  • 35
  • 244
  • 286