JavaScript30 - Day 6

By Camilla Krag Jensen naxoc |

Day 6 of #javascript30 is an ajax type ahead form. I learned about the fetch API, promises, asynchronicity, and I might finally understand 'const'.

Fetch API

In the past I have used jQuery's ajax(), get(), or getJSON() for requesting stuff or I have gone to Stack Overflow and copied an XMLHttpRequest like the one below because there was no way I'd remember how to do that from time to time.

var xmlHttp = new XMLHttpRequest();
  xmlHttp.onreadystatechange = function() {
    if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
      console.log(xmlHttp.responseText);
  }
  xmlHttp.open("GET", endpoint, true); // true for asynchronous
  xmlHttp.send(null);

It so much easier to use fetch():

let cities = [];

fetch(endpoint)
  .then(blob => blob.json())
  .then(data => cities.push(...data));

Promises

fetch() returns a Promise object and when the data has been fetched at some point, the code in the then()s is executed. It is an asynchronous call, so it will be executed at some point. This is important and I actually ran into some problems with console.loging my results. My cities array was empty, but if I console.loged the data inside the call to then(), I had the array filled? It was a good learning experience to run into because I realized the asynchronousness (is that a word?) of the promises. I went to Stack Overflow and copied a function that would "sleep" for 2 seconds and then I could console.log my array of cities. Slow internet connection made me understand promises better. Thanks, wonky internet connection!

const finally clicked for me

I finally understood what const is in JavaScript. It is not the same as a constant in PHP, where the value cannot change, so they were a little confusing to me. I went and read the documentation and this part sums it up nicely:

The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned. For instance, in the case where the content is an object, this means the object's contents (e.g. its parameters) can be altered.

So you can change a const, just not reassign it.

RTFM

This lesson taught me a lot and I took my time reading the documentation for the things I was using. It can hardly surprise anybody that reading the manual is a good idea, but I am actually pleasantly surprised at how good and very readable the docs on MDN (Mozilla Developer Network) are. So if you are also trying to learn more JavaScript, I really recommend spending some time just reading about what you are learning instead of what I normally do which is just hunting for something to copy paste.