Lecture 11
Lecture 11
Programming and
Promises
Lecture 11
Today’s Agenda
● Asynchronous Programming
● Promises
Asynchronous Programming
Synchronous vs Asynchronous
Synchronous vs Asynchronous
(function() {
...
function init() {
console.log('page loaded');
qs('button').addEventListener('click', clickHandler);
showMenu();
}
function showMenu() {
id('menu').classList.remove('hidden');
}
function clickHandler() {
/* Your code */
}
})();
Callbacks?
Callbacks are a very powerful feature in event-driven programming.
Why do you think it's useful to have the ability in the JavaScript language to
pass callback functions as arguments to other functions like
addEventListener and setTimeout in JS?
Asynchronous Programming
The JS programs we've been writing are naturally asynchronous
setTimeout(callbackFn, 2000);
setTimeout(function() {
...
}, 2000);
setTimeout(() => {
...
}, 2000);
Why is JavaScript so different?
Java is often used to build systems.
● Objects are great to compose together to build complex systems.
● Systems must be reliable - a benefit of strict types, compiling, and well-
defined behavior in Java.
JavaScript is used to interact and communicate.
● It listens.
● It responds.
● It requests.
Whereas in Java, programs often have a well-defined specification (behavior),
JS has to deal with uncertainty (weird users, unavailable servers, no internet
connection, etc.)
What if?
let myBtn = qs('button:nth-child(1)');
while (!myBtn.clicked) {
// twiddle our thumbs
}
console.log('"Finally Been Clicked", starring Drew Barrymore');
orderPizza()
.then(verify)
.then(eat)
.then(pay)
.catch(badPizza);
Promises Promises are a sort of contract:
● Something will happen
● You can have multiple things happen.
● And catch any errors.
Promises on MDN
Creating a Promise
function description
let promiseObj = new Promise(executorFn) Creates a new Promise object with the executorFn
You define this function and pass it into the Promise constructor
Back to that Pizza
function orderExecutor(resolve, reject) { // reject not required here
console.log('making our pizza...');
setTimeout(resolve, 5000);
}
function eat(value) {
return value + ", and now it's gone";
}
function eat() {
return new Promise(eatExecutor);
}