Posted almost 7 years ago. Visible to the public.

JavaScript: Writing asynchronous code [2.5d]

Reading

Understand how asynchronous JavaScript works:

Browse the internet to answer the following questions:

  • What are “synchronous” or “blocking” APIs versus “asynchronous” APIs?
  • Why does fetch() 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?

Exercises

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.

fetch()

Write a function that:

  • Fetches a list of records via fetch() (either as a JSON array or as a pre-rendered HTML fragment).
  • Insert the list into the DOM.
  • Slowly fade in the list's opacity.
  • Allow your caller to run code when the fade-in animation is done.

Create two different implementations of this:

  1. Using callbacks
  2. Using promises

Owner of this card:

Avatar
Henning Koch
Last edit:
8 months ago
by Henning Koch
Posted by Henning Koch to makandra Curriculum
This website uses short-lived cookies to improve usability.
Accept or learn more