About 1.1 hours
- 30 minutes for Demonstration
- 30 minutes for Independent Practice
- 10 minutes for Checking Understanding
- Know how to create a Javascript function, named and anonymous.
- Know what Asynchronous means.
- Callbacks are an important part of Javascript's history, any asynchronous language's actually. You will learn about "callback hell" and how Promises help you reach heaven again.
Apprentices will be able to:
- Identify and write callbacks and Promises.
- Know when to use a Promise.
- callback
new Promise(((resolve, reject) => {}))promise.then()Promise.all()
- Non-existent, jump to Demonstration.
- A callback is just a function that is called when another function is done.
- We have them because Javascript is asynchronous.
- Promise is a class of object. Think of it as a literal promise. Like a task that you promise to finish later.
- It's built into most browsers(all but ie: Browser Support).
- It's different than the object return by jQuery's AJAX, but similar.
- It's the object returned by
fetch(like AJAX but built into most browsers)
- Open up dev console in browser.
- Write a function and pass in another function(the callback) that gets called inside the first function.
- Show "callback hell" but passing in functions as parameters like 4 levels deep. There's got to be an easier way to write things that depend on eachother, right?
- Create a
Promiseand pass a callback to itsthenmethod. Create callback that usessetTimeoutto mimic latency (network/database delay). The callback passed tosetTimeoutwill resolve the promise (use the parameter). - Chain another
thenwith a callback that console.logs something to show the flow of execution.
- Play around in your favorite browser's dev console.
- Create several Promises, each with callbacks with different
setTimeouttimes. - Then call them in parallel, which Promise method can you use for that?
- Chain a
catchmethod (like how you did withthen) to this promise, and pass another callback. Which Promise parameter can you use to pass control fromthentocatch? - Look at the object returned by creating a Promise. What properties does it have? Look for its
status. - Check its
statusagain, has it changed?
- Why do we use callbacks?
- Define a Promise in your own words.