DEV Community

Joy Palumbo
Joy Palumbo

Posted on

Javascript Async Callbacks

Let's talk a little bit about async callbacks. First we need to talk about synchronicity vs asynchronicity. Javascript is a syncronous, single threaded language. What that means is that javascript reads code line by lineand reads everything in order, from top to bottom. Let's take a look at a simple example:

var a = 1;
var b = 2;

In the example above, javascript will read/run each line in order. "a" will console 1st, then "b" will console. In an example like this, all is fine. But what about when we start building apps. No problem right? Actually, this can cause a lot of problems. There are many situtions where we have code that does something, such as query a data base, or requests info from an api. Those querys can take a long time. We don't know how long it will take to receive that data back. Because Javascript is syncronous, it will send the request, then keep on going and run the rest of the code. This can cause a lot of problems, such as our data being undefined. Lets look at an example of how this might happen:

```function getData() {
var data;
$.get("This is a get request, trying to get data", function(response) {
data = response;
return data;

var data = getData();
console.log("The data is: " + data);```

This function is syncronous. We have a get request that is requesting data but it might be a while for that data to come back. In the meantime, javascipt will move to the next line and return data. But we haven't received any data back so the data will return undefined so in the next couple of lines, when we console.log data, it will console.log "undefined". This is no beuno. If a developer is not aware of such issues, this could cause a lot of problems and a big headache. Luckily there is a solution...


Asyncronicous code allows us to run long network requests and queries without holding up other code. 3 common ways to do this is callbacks, promises and async/await. Promises and async/await are great but today we're talking about callbacks.

Callbacks are functions that are passed into other functions as a paramater. Named functions or annonymous functions can be used. Let's look at an example of how to use a callback:

Here we have a function called "greeting". We will use this as our callback function.

function greeting(name) {
 console.log(`Hello ${name}, welcome to OpSpark!`);

Below, we have another function that takes a callback as one of it's paramater and we will pass in the greeting function as the callback.

function introduction(firstName, lastName, callback) {
 const fullName = `${firstName} ${lastName}`;

introduction('Pickles','McPickleton', greeting); // Hello Pickles McPickleton, welcome to opSpark!

When "introduction" is ran, it calls the callback and "greeting" doesn't run until it is called inside "introduction". This is just a basic example but callback functions are very handy in succesfully passing or manipulation data.

Callbacks are good for short, asyncronous operations but you should be carefully not to nest too many callbacks because you will enter callback hell which can make it very hard to debug your code. If you think you are going to have more than 3 or so nested callbacks, it's best to use a promise or asyn/await.

Alt Text

Alt Text

In conclusion, when using javascript, it's best to be asyncronous and one way to do this is to use callbacks. Callbacks can be very helpful, but be careful not to get too carried away.

Top comments (0)