JavaScript 9 - Async, Callbacks, Promises

Projected Time

About 1 to 2 hours

Prerequisites

Motivation

Objectives

Apprentices will be able to:

Specific Things to Learn

Materials

Lesson

Things to Remember

Guided Practice

  1. Open up dev console in browser.
  2. Write a function name counter and pass in another function(the callback) named cb as parameter.
function counter(cb) {
    console.log('inside counter function ');
    cb(); //here callback function gets called by counter()
}
counter(function(){
    console.log('inside callback function');
});
  1. If we again call counter() inside cb() definition then we can see a pattern of deep nesting, known as callback hell.
function counter(cb){
  console.log('inside counter function ');
  cb();
}

counter(function(){
  console.log('inside callback function');
  counter(function(){
    console.log('inside callback function');
   });
});

There’s got to be an easier way to write things that depend on each other, right? Promises.

  1. Create a Promise and pass a callback to its then method. Create callback that uses setTimeout to mimic latency (network/database delay). The callback passed to setTimeout will resolve the promise (use the parameter).
  2. Chain another then with a callback that console.logs something to show the flow of execution.
const isMomHappy = true;
// Promise
const willIGetNewPhone = new Promise(
    (resolve, reject) => {
        if (isMomHappy) {
            const phone = {
                brand: 'Samsung',
                color: 'black'
            };
            resolve(phone);
        } else {
            const reason = new Error('mom is not happy');
            reject(reason);}
     }
);

const showOff = function (phone) {
    const message = 'Hey friend, I have a new ' +
                phone.color + ' ' + phone.brand + ' phone';
    return Promise.resolve(message);
};

// call our promise
const askMom = function () {
    willIGetNewPhone
        .then(showOff)
        .then(fulfilled => console.log(fulfilled))
        .catch(error => console.log(error.message));
};
askMom();

Independent Practice

Challenge

Check for Understanding

Supplemental Materials