Asychronicity in JavaScript

[Pages:33]Asynchrony in JavaScript

Alper Sarikaya (@yelperalp)

CS 638 JavaScript & Web Programming November 17th, 2015

Asynchrony in JavaScript

How we handle it in JavaScript (and jQuery, D3, etc.)

Requesting data in JavaScript (and jQuery, D3, etc.)

Event Handling (and jQuery, D3, etc.)

Reactive Programming

WebSockets/binary data/WebGL

WebWorkers

-

JavaScript is single-threaded!

This means:

Asynchronous events can return and interrupt

Long processing work can block interrupts from occurring (page appears to hang)

Only one thing can be done at a time

(except if you use WebWorkers; more later)

Handling Asynchronicity

Want to (without reloading page):

Get data from datastore on the webserver Update state on webserver based on user action Post a message, record a vote for others to see Retrieve some video/binary data to display to client

Handling Asynchronicity

Make an XmlHttpRequest (XHR) Ajax programming model

Asynchronous JavaScript and XML

var xhr = new XMLHttpRequest(); xhr.open('GET', 'DoSomething.php', true); xhr.responseType = 'json';

xhr.addEventListener('load', function() { if (xhr.status == 200) { loadBinaryData(xhr.response); } else { console.warning("failed to load (status: %d)", xhr.status); console.trace(); }

});

xhr.send(null);

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download