Posted almost 3 years ago. Visible to the public.

Javascript: Writing asynchronous code

Reading

Browse the internet to answer the following questions:

  • What are “synchronous” or “blocking” APIs versus “asynchronous” APIs?
  • Why does $.ajax not simply return the response from the server?
  • Why is asynchronous code such a big issue in Javascript (as opposed to the code we usually write in Ruby)?
  • What are "callbacks" in Javascript? Can you find examples for libraries that use callbacks to deal with asynchronity?
  • What are "promises" in Javascript? Can you find examples for libraries that use promises to deal with asynchronity?

Look at the jQuery API for the following functions:

  • $.deferred
  • $.when

Discuss the points above with your mentor.

Exercises

$(element).animate

Animate something using $(element).animate, then do something after the animation ends.

Create two different implementations of this:

  1. Using callbacks
  2. Using promises

$.ajax

Perform an AJAX request using $.ajax, then do something after the request returns.

Create two different implementations of this:

  1. Using callbacks
  2. Using promises

afterMillis

Create an implementation of setTimeout that returns a promise rather than taking a callback. Name this new function afterMillis. Internally, it can make use of setTimeout, but the API should be like that:

Copy
afterMillis(1000).then(function() { console.log('One second has passed!'); });

As a bonus, also reject the promise if the caller passes a negative argument to afterMillis.

Author of this card:

Avatar
Henning Koch
Last edit:
12 months ago
by Michael Leimstädtner
Posted by Henning Koch to makandra Curriculum
This website uses cookies to improve usability and analyze traffic.
Accept or learn more