Home Logic Ubuntu (Linux) Blog

NodeJS: Callbacks

A callback is a function that is passed into another function.

Hover over the ➼ words in bold.

          // calculate sales tax
          function calcTax(bill,callback){
            var tax = bill * .06;

        // calculate deduction
          function calcDeduction(tax){
            var total = tax * .20;
            // log deduction

          // Make Message
          function makeMessage(tax){
           var message = "You paid " + tax + " in sales tax.";

calculate tax -
The bill and a callback are passed into this function. When the function's code is done executing, the callback will be executed with tax as the parameter.

calcDeduction -
This is a function that takes in tax as a parameter and calculates the amount of a deduction. It then displays the amount.

makeMessage -
This is a function that takes in tax as a parameter and displays a friendly message with the amount.

      var myBill = 100;
      // display message
      // display deduction

calcTax: senario 1 -
myBill and makeMessage are passed into calcTax.

calTax: senario 2 -
myBill and calcDeduction are passed into calcTax
callback functions -
makeMessage is passed into calcTax as a callback.
calcDeduction is passed into calcTax as a callback.

The code above is not a realistic example of callbacks. It is meant to be a simple example of the concept. In the next lesson, we will look at a realistic example.

Callbacks & & Asynchronous Code

When a callback is passed into a function, the parent function becomes asynchronous. In the example above, makeTax would be an asynchronous function. makeTax takes in two parameters: the amount of the bill and a callback function. Once all the code in makeTax is done executing, you can pick a callback function to pass in. It can be any function that takes the tax calculation as a parameter.

Common Asynchronous NodeJS functions

✶ Database Queries
✶ Reading Files
✶ Creating Files
✶ Parse Data


Realistic Example

Tasks that take longer require callbacks. Say you are displaying a blog page. The blog articles are stored in a PostgreSQL database. Making the blog takes a long time, because it has to interact with the database. The other page elements are made with html and client side JavaScript. While makeBlog is waiting for a response, the rest of the page can begin displaying,

db.query(statement,values, function(err,res) {
  if (err) {
    throw err;
  else {
    var blog = JSON.stringify(res.rows);

NodeJS Queries covers queries in more detail.

Previous Lesson | Next Lesson