Raghavendra
Raghavendra

Reputation: 5387

How to write an asynchronous JavaScript method?

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?

Upvotes: 0

Views: 198

Answers (1)

andyf
andyf

Reputation: 3350

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

Upvotes: 1

Related Questions