Callbacks

Learn what is a callback in JavaScript and how to avoid the callback hell.

Take a look at this code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
fs.readdir(source, (err, files) => {
if (err) {
console.log('Error finding files: ' + err.message)
} else {
files.forEach((filename, fileIndex) => {
console.log(filename)
gm(source + filename).size((err, values) => {
if (err) {
console.log('Error identifying file size: ' + err.message)
} else {
console.log(filename + ' : ' + values)
aspect = (values.width / values.height)
widths.forEach((width, widthIndex) => {
height = Math.round(width / aspect)
console.log('resizing ' + filename + 'to ' + height + 'x' + height)
this.resize(width, height).write(dest + 'w' + width + '_' + filename, err => {
if (err) console.log('Error writing file: ' + err.message)
})
}.bind(this))
}
})
})
}
})

Callback paradigm may cause headache and few troubles unless you know what are you doing. In order to avoid that situation to you I’ll give you some useful information about it.

Callbacks are usually used by async functions. The function does some calculations and then call a function that has been passed as parameter.

Think about a function which downloads a file from the Internet:

1
2
const file = download('http://link.com/file.zip');
console.log(file); // undefined

Our function didn’t finish but we try to print the output. This is an example which we must to use a callback. With promises or async/await this is not needed any more, but you may see functions that only accept callbacks, so I’ll explain it.

The following code uses a callback:

1
2
3
4
5
6
7
download('http://link.com/file.zip',(err,file) => {
if(err){
console.error('Something went wrong',err);
} else {
console.log(file);
}
});

Give it a name

You also need to give a name to complex callbacks in order to avoid callback hell. In our example we should do it as follow:

1
2
3
4
5
6
7
8
9
const handleResponse = (err,file) => {
if(err){
console.error('Something went wrong',err);
} else {
console.log(file);
}
};

download('http://link.com/file.zip',handleResponse);

References