300 JavaScript: Writing asynchronous code [2.5d]

Posted Almost 8 years ago. Visible to the public.

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 asynchronicity?
  • What are "promises" in JavaScript? Can you find examples for libraries that use promises to deal with asynchronicity?

Exercises

atFullSecond()

Create an implementation of setTimeout that returns a promise rather than taking a callback. Name this new function atFullSecond, as it should wait for the remaining milliseconds until the next second starts. For example, at 13:23 and 441 milliseconds, atFullSecond(1) should wait for 559 milliseconds before triggering the callback function.

Internally, it can make use of setTimeout, but the API should be like that:

atFullSecond(2).then(function() {
  console.log(`waited until exactly ${new Date}`);
});

new Date().getUTCMilliseconds() gives you access to the current millisecond offset.

As a bonus, also reject the promise if the caller passes number smaller than one to atFullSecond.

fetch()

Write a function that:

  • Fetches a list of records via fetch() (either as a JSON array or as a pre-rendered HTML fragment).
  • Inserts the list into the DOM.
  • Slowly fades in the list.
  • Allows its caller to run code when the fade-in animation is done.

Create three different implementations of this:

  1. Using callbacks
  2. Using promises and then()
  3. Using promises and async / await
Avatar
Henning Koch
Last edit
6 days ago
Michael Leimst├Ądtner
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra Curriculum (2015-08-20 15:01)