JavaScript Remote:
Lesson 13: Promises, ES6 continued, and Lab Time


REview
- What is "inheritance"?
- What is the purpose of promises?
- What are some key features of ES6?
- Are promises native in JS?

Using Promises


The 3 stages of Promises
- Pending: we have no idea what's going to happen to our request, but it has been fired.
- Resolved: Yay, everything worked!
- Rejected: Boo, something failed.

The skeleton, Vanilla
new Promise(/* executor*/ function (resolve, reject) { ... } );
var p = new Promise(function(resolve, reject) {
// Do an async task async task and then...
if(/* good condition */) {
resolve('Success!');
} else {
reject('Failure!');
}
});
p.then(function() {
/* do something with the result */
}).catch(function() {
/* error :( */
})
Why Promises: Events and ugly callbacks
var img1 = document.querySelector('.img-1');
img1.addEventListener('load', function() {
// woo yey image loaded
});
img1.addEventListener('error', function() {
// argh everything's broken
});
Why Promises: Events and ugly callbacks, more
var img1 = document.querySelector('.img-1');
function loaded() {
// woo yey image loaded
}
if (img1.complete) {
loaded();
}
else {
img1.addEventListener('load', loaded);
}
img1.addEventListener('error', function() {
// argh everything's broken
});
The vanilla promise
var promise = new Promise(function(resolve, reject) {
// do a thing, possibly async, then…
if (/* everything turned out fine */) {
resolve("Stuff worked!");
}
else {
reject(Error("It broke"));
}
});
promise.then(function(result) {
console.log(result); // "Stuff worked!"
}, function(err) {
console.log(err); // Error: "It broke"
});
Let's try it
Let's use the Bacon Ipsum API:
https://baconipsum.com/json-api/
(No offense to vegetarians/vegans intended)
- Construct a codepen with promise.
- Use the promise to query the API.
- console.log the data after a successful return.
- Optionally, populate the data in the DOM with a loop.

Let's try it (~30m)
Let's do this in groups. Always feel free to shout out if you have questions. Remember your skeleton:
var promise = new Promise(function(resolve, reject) {
// do a thing, possibly async, then…
if (/* everything turned out fine */) {
resolve("Stuff worked!");
}
else {
reject(Error("It broke"));
}
});
promise.then(function(result) {
console.log(result); // "Stuff worked!"
}, function(err) {
console.log(err); // Error: "It broke"
});
Let's try it (~30m)
- Get your Ajax call working in vanilla JS.
- console.log your data
- Work on the promise!

More ES6!

Project 2 Lab Time
Exit Tickets and Thanks!

JavaScript Remote, Lesson 13: Promises, ES6, and Lab Time
By Sonyl Nagale
JavaScript Remote, Lesson 13: Promises, ES6, and Lab Time
- 16