My Dissertation - Week 5

I didn't do an awful lot of work this week, I was very busy with not-dissertation-things. I did manage to complete a code review and refactor my current codebase for the server. Although these were the only tasks I accomplished this week..


Refactoring

I refactored a lot of code for my server because I hadn't used any Promises while developing, I just got each route working!

It's okay though, this was planned! So I bought a book called JavaScript with Promises, it's really good. I also had a friend talk me through Promises, thanks Fitz!

Promises

A Promise (MDN link) is a super-useful method of managing asynchronous JavaScript. A Promise is an object that represents a value which may be available sometime, or never.


let myFirstPromise = new Promise((resolve, reject) => {
  // We call resolve(...) when what we were doing async succeeded, and reject(...) when it failed.
  // In this example, we use setTimeout(...) to simulate async code. 
  // In reality, you will probably be using something like XHR or an HTML5 API.
  setTimeout(function(){
    resolve("Success!"); // Yay! Everything went well!
  }, 250);
});

myFirstPromise.then((successMessage) => {
  // successMessage is whatever we passed in the resolve(...) function above.
  // It doesn't have to be a string, but if it is only a succeed message, it probably will be.
  return "yay! " + successMessage
}).then((successMessage) => {
  console.log("It worked, " + successMessage)
});

Code adapted from MDN example.

You can chain together promise methods (.catch and .then etc.) which means that you can iteratively adjust your data, which is really nice. In the example above I add a string to the beginning of the successMessage and in the next .then I print out a string and the message. If you comment out the second .then method and replace the return with a console.log in the first, then you'll be able to see the difference in action.

.catch is an important method because it catches a promise that hasn't been fulfilled for some reason, it works just like .then, you can chain a bunch of these methods.


In my server code I send a lot of API requests and I use promises to handle the responses to these requests, I even use Promise.all() to wait until all my promises are ready before using the data.


const googleMapsClient = require('@google/maps').createClient({
key: google_api_key,
//enable in-built promise support
Promise: Promise
});

var origin_coords = '51.45772896357182,-0.9720191359519958';
var destination_coords = '51.455171860200345,-0.9698948264122009';
var transport_modes = ["driving", "walking", "bicycling", "transit"];

Promise.all(transport_modes.map(value => {
return googleMapsClient.directions({
  origin: origin_coords,
  destination: destination_coords,
  mode: value
})
//using the in-built promise support of the Google Maps npm module
.asPromise()
//get the route data from the response json
.then(res  => {return res.json.routes;})
//then use that as the value and the transport mode as it's key
.then(res  => {return {[value]: res};})
//if there's an error, catch it and return this
.catch(err => {return err;});
}))
//collects all promises and logs it in console
.then(data => {console.log(data);});

You need to replace google_api_key with your own key!

This code uses the Google Maps npm module and Promises, to send 4 requests to Google Maps Directions API. It gets a route for each mode of transport, where each request is a promise, using Promise.all it collects the results of all promises and then returns that as a promise.

Using Promise.all collects whatever the result of each promise is, which is why I don't have a .catch() for it, because it will have data returned from each promise from either then or catch.

If you try doing something like this without Promises, it quickly becomes very messy code. Promises make async code more manageable and readable.


Code Review

I performed a code review, which is where you go through your code and review it's design. Is it overly complex? Are there any hidden bugs?

I performed this as part of a pair with a housemate, this was good because it meant that I had to justify my design decisions and my review-partner had only my comments to go on. This resulted in some more in-depth comments in my code!

There were no major issues found in the code review, there were a few instances of explaining why I had used let instead of var and things like that which resulted in some learning.

So the Code Review went pretty smoothly and the results of it were making my code more understandable to any outsiders.


That's all for this sprint. I'm starting on the front-end now, so I have most of my project at a stage where I can show it off! So next post should involve lots of drawings, maybe even some wireframes!