Understanding Asynchronous Code in Layman’s terms

I’m not sure where this function is being used, but the point of callbacks is that you pass them into some function that runs asynchronously; it stores your callback away, and when that function is done with whatever it needs to do, it will call your callback with the necessary parameters. An example from front-to-back is probably best.

Imagine we have a framework, and in it there is an operation that runs for a long time, fetching some data from the database.

function getStuffFromDatabase() {
  // this takes a long time
};

Since we don’t want it to run synchronously, we’ll allow the user to pass in a callback.

function getStuffFromDatabase(callback) {
  // this takes a long time
};

We’ll simulate taking a long time with a call to setTimeout; we’ll also pretend we got some data from the database, but we’ll just hardcode a string value.

function getStuffFromDatabase(callback) {
  setTimeout(function() {
    var results = "database data";
  }, 5000);
};

Finally, once we have the data, we’ll call the callback given to us by the user of the framework’s function.

function getStuffFromDatabase(callback) {
  setTimeout(function() {
    var results = "database data";
    callback(results);
  }, 5000);
};

As a user of the framework, you’d do something like this to use the function:

getStuffFromDatabase(function(data) {
  console.log("The database data is " + data);
});

So, as you can see data (same as response and postData in your example) came from the function that you pass your callback into; it gives that data to you when it knows what that data should be.

The reason you can’t set a value in your callback and use it outside the callback is because the callback itself doesn’t happen until later in time.

//  executed immediately  executed sometime in the future
//      |                  |       by getStuffFromDatabase
//      v                  v
getStuffFromDatabase(function(data) {
  var results = data; // <- this isn't available until sometime in the future!
});

console.log(results); // <- executed immediately

When the console.log runs, the assignment of var results hasn’t happened yet!

Leave a Comment