Asynchronous Programming – Javascript Exercise

Learning Goals

  • Software design approaches and patterns, to identify reusable solutions to commonly occurring problems
  • Apply an appropriate software development approach according to the relevant paradigm (for example object oriented, event driven or procedural)

Programs Used

Part 1 – Promisify busboard

Fork the repository and follow the steps in the readme. This repository contains part of the BusBoard exercise from the bootcamp – it prompts for a postcode and will return the bus routes heading to that area.

Check that you can run the app by running npm install followed by npm start to see it work.

Your goal is to promisify busboard.

  1. Update consoleRunner.js so that it uses promises instead of callbacks.
  2. Make sure you catch all errors and that you are able to disambiguate between error cases.
  3. Update the code even further to use async/await.

Remember to commit early and often!

Part 2 – Promise all

The below piece of code uses the result of two independent promises:

const p1 = Promise.resolve(4);
const p2 = Promise.resolve(8);
 
p1.then((result1) =>
     p2.then((result2) =>
        console.log(result1 + result2)
  )
);
  • Use Promise.all to use the result of the promises instead of nesting them.
  • What is the difference between awaiting on the two promises and using Promise.all?

Part 3 – Handle errors in Promise.all

The following two functions need to be executed in sequence but occasionally throw an error:

let p1 = new Promise(function(resolve, reject) {
    setTimeout(function() {
        if(Math.random() < 0.5) {
            resolve("success");
        } else {
            reject(new Error("promise rejected"));
        }
    }, 500);
});
 
let p2 = new Promise(function(resolve, reject) {
    setTimeout(function() {
        resolve();
    }, 1000);
}).then(function() {
    if(Math.random() < 0.5) {
        return "success";
    } else {
        throw new Error("error thrown");
    }
});
 
p1.then(function(result) {
    return p2;
});
  • Make sure that all errors are caught.
  • Can your code disambiguate between the two errors? If not, how would you modify it so that it can?
  • If you were to run the promises in parallel using Promise.all and change the promises to always return an error, which error(s) do you expect to see in the catch block? Once you have an answer, change the code to verify your assumption.
  • Use Promise.all to run both promises, but make sure that it waits until both have completed (whether they resolved or rejected).