Posted almost 7 years ago. Visible to the public.
JavaScript: Writing asynchronous code [2.5d]
Reading
Understand how asynchronous JavaScript works:
- Read Henning's presentation about asynchronous Javascript (there's also a German video presentation in our shared folder)
- Read about Promise Archive
- Read about async Archive / await Archive .
- Read Don't throw exceptions from async functions
- What Color Is Your Function Archive
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:
CopyafterMillis(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:
- Using callbacks
- Using promises