Eluding the Triangle of Doom

Do you like callbacks? How about callbacks in callbacks? Okay but… how about callbacks in callbacks in callbacks in callbacks? Nope, me either. You see, callbacks are great. They can help us do things that we otherwise could not. What I am referring to here, is use asynchronous functions… AND have our code work.

Javascript is a single threaded language. This means that Javascript can only do one thing at a time, and it executes code in a single sequence . Some other languages are multi-threaded, and each thread can execute code simultaneously. What this means for us as Javascript programmers, is that sometimes we may need to start a process that is not instantaneous. This arrises a problem because javascript continues executing the next line of code in the sequence, and often times you end up with an undefined variable somewhere because the process in which you started never got a chance to finish.

This is where callbacks come into play, we can pass a callback into a function to ensure that the callback does not get called until the function we pass it into completes running. This makes asynchronous function calls possible in Javascript, but it comes with a downside. When you’re dealing with a bunch of async functions, that means a lot of nested callbacks, which create the triangle of doom.

exports.getNextUniqueId = (cb) => {
readCounter((err, fileData) => {
if (err) {
throw err;
cb(null, 0);
} else {
writeCounter(fileData + 1, (err, counterString) => {
if (err) {
throw err;
} else {
console.log(counterString);
cb(null, counterString);
}
});
}
});
};

This example shows a callback nested inside of a callback. If that is not already confusing, just imagine if we added a few more.

So, in order to make our code work, and be a bit more readable, we can use Javascript promises instead of callbacks. A promise is basically a function, that promises to eventually return either an error or a value. This also helps us with async function calls because we can create a promise to hold the value that we need, and once we have the promise we can move it wherever we need to, even if it has not resolved yet!