moe
moe

Reputation: 45

Seeking clarification about asynchronous javascript

I am a beginning javascript programmer. I have been trying to understand asynchronous javascript but I wanted to clear up a couple of things.

I understand that javascript runs in a single thread and that you can use callback functions to make your code asynchronous, but I am confused about what makes a callback function asynchronous or not.

A lot of the async callbacks seem to follow a pattern where a function has as its parameters a certain action and then a callback function which is to execute when that action is complete:

jQuery.get('page.html', function (data) {
    console.log("second");
});
console.log('first');

What is it specifically that makes the callback in the parameter here execute at a later time? Is it that the get method here is pre-defined as some sort of a special method (because it fetches a file) that if you pass a function as a second parameter, it behaves in a asynchronous manner?

How can you make functions that you would write yourself asynchronous?

Thanks

Upvotes: 3

Views: 58

Answers (1)

jamison
jamison

Reputation: 311

It could be one of several things that makes asynchronous code asynchronous:

  • Timer Events (i.e. setTimeout() and setInterval(), which each accept callback functions as arguments that they execute at a later time)
  • DOM Events (i.e. attaching an event listener with a callback function to an HTML element or other DOM node, in which case your callback function is executed upon that event firing)
  • Other APIs provided by the browser (i.e. XMLHTTPRequest, which emits events based on things the browser does natively under the hood)
  • In Node.js or similar serverside environment, any I/O libraries that directly access resources such as disks or the network

Generally speaking, setTimeout() and setInterval() are the only vehicles for asynchronous execution in native JS (as opposed to the DOM, browser, or other APIs provided by the specific runtime)

In the case of your example, jQuery's .get() method is simply a wrapper for the browser's XMLHTTPRequest API, which creates a new XHR object that in turn emits events based on the status of the HTTP request, and attaches listeners with callbacks to those events.

Upvotes: 1

Related Questions