CodeNewbie Community

Arpit Mathur
Arpit Mathur

Posted on

The JavaScript keyword that has most wasted my time

Building Jax, the JavaScript chatbot has required me to spend a lot of time writing code in JavaScript and Dart. Modern JavaScript has added a lot of amazing new features, and one of the best is the new way of handling asynchronous code, like that required for making network calls.

In earlier days, the only way to call an asynchronous function was to pass it an additional callback function that would get invoked when the function completed. Take a look at the example below that uses jQuery to make a "GET" request.

$.get( "ajax/test.html", onData);
Enter fullscreen mode Exit fullscreen mode

The second parameter there is the function that will be called when the data was loaded. Unfortunately, this made the code hard to read since anything that happened after the code was loaded had to be written in a separate function

function loadData(){
  const dataURL = "/data.xml"
  $.get( "ajax/test.html", onData);
}

function onData(data){
  console.log("data loaded", data)
}

Enter fullscreen mode Exit fullscreen mode

Modern JavaScript uses the keyword await which makes the code a lot more readable.


async function loadData(){
  const dataURL = "/data.xml"
  let data = await fetch(dataURL);
  console.log("data loaded", data)  
}

Enter fullscreen mode Exit fullscreen mode

This makes the code so much easy to read. Unfortunately, there is one possibility of a bug. If you are using async methods and want your code to pause and wait for the result, don't forget to use the await keyword when you call the function. Not using it is telling the browser that you don't need the data immediately and the JS engine will immediately run the next line of code, which will log a null value for the data because the data hasn't been loaded yet.

I just wasted 3 hours on a bug caused by not awaiting an asynchronous operation, and it wasn't the first time 😅

=====

Btw, if you are interested, I'd love for you to check out Jax and let me know what you think :)

Discussion (0)