COVID19 Lockdown Dev Log – Day 25, Callback NodeJs

What I Worked On

A weather app in NodeJs, which can display the current weather in the location you choose.

What I Learned

I got deep into the “Callback” pattern in NodeJs. This was due to having to fetch data asynchronously in the weather app I’m coding. I’ve had a general idea of what callback functions are, but it was nice to dive into it and experiment with them in synchronous and asynchronous functions.

Let’s take two examples to illustrate what I learned. A synchronous function which directly returns a value:

const add = (numOne, numTwo) => {
  return numOne + numTwo
}

add(5, 2) //outputs 7

A synchronous function which instead uses a callback function to return the value. The value is returned once the callback has completed. This is called continuation-passing style:

const add = (numOne, numTwo, callback) => {
  callback(numOne + numTwo)
}

console.log("before add()")
add(5, 2, (result) => {
 console.log(result)
}) //outputs 7
console.log("after add()")

The code (script in this case) isn’t continuing to execute until it has completed the callback function. The output would be:

before add()
7
after add()

In some cases this is probably what you want, but what if you would need to fetch data in an app? That can take extra milliseconds and you don’t want to just have your app “frozen” until the data is fetched.

To solve that problem you can use callback functions asynchronously. To simulate a request for data I use the NodeJs API ‘setTimeout’:

const add = (numOne, numTwo, callback) => {
    setTimeout(() => {
        const result = numOne + numTwo

        callback(result)
    }, 2000)
}

console.log("before add()")
add(1, 4, (sum) => {
    console.log(sum) // outputs 5
})
console.log("after add()")

Since the callback is now asynchronous, the app will not “freeze” until the timeout has passed 2 seconds. It will execute the console.log ‘before’ and ‘after’ and when 2 seconds has passed it will console.log the sum of ‘add()’:

before add()
after add()
5

These examples are a bit simple, but if you want to see how I utilized it in my weather app you can have a look at the code on GitHub here 😀

What Distracted Me During The Day

  • Had to do some laundry 😀

Resources

NodeJs Fundamentals – https://subscription.packtpub.com/book/web_development/9781783287314