0

I have been working on async programming in JavaScript recently. I've been coming through many code snippets and also in jQuery methods, where if we pass a callback function as a parameter to another function, it executes asynchronously. The call back is executed after the execution of that function completes.

I have been through some answers on Stack Exchange network on this topic. One guy said we cannot make our code asynchronous unless we depend on a native method for that functionality

see here https://stackoverflow.com/a/9516967

alse here https://softwareengineering.stackexchange.com/a/194591

Another guy said that just passing callbacks to events makes our code asynchronous. https://softwareengineering.stackexchange.com/a/194581

My question is that what makes code asynchronous, by just passing a callback, or should we depend on native methods like setTimeout or setInterval to attain async functionality?

Community
  • 1
  • 1
Raghavendra
  • 5,281
  • 4
  • 36
  • 51
  • You can't achieve asynchronous javascript by `setTimeout` or `setInterval`. That simply goes against the meaning of "real" asynchronous. Timers can't be asynchronous as they depend on so much thing. Though if I continue my monolog, I think I will come to the point where nothing is "real" asynchronous in computer (ofcourse if we don't consider that code can run on multiple threads or even multiple cores) :) – Arman P. Feb 07 '14 at 05:25
  • the easiest method is to create a `timer` as you have stated. This still requires the client to continue running your code or the async code will stop executing...Server side RESTful calls would allow you to make a rest call (async run on server) then get a callback this question however is architecture in nature and thereby this isn't the right forum for it. – abc123 Feb 07 '14 at 05:27

1 Answers1

1

Asynchronous means JavaScript is non-blocking when handling I/O.

Here is a sample from Node.js in Action:

  $.post('/resource.json', function (data) { // I/O does not block execution
      console.log(data);
  });

Notice that the code was NOT written like this:

 var data = $.post('/resource.json');
 console.log(data);
andyf
  • 3,262
  • 3
  • 23
  • 37