Asynchronous Functions And Callback Triangle
Asynchronous functions are functions that handle some request, then return the result when the operation is complete. Now, while this is going on the program is still executing instruction after instruction; execution is not paused. The way these functions were traditionally written were as functions that take other functions.
Here’s an example from a project of mine.
As you can see, if I want to enforce any order for the instructions to be executed, I have to pass a callback function as a parameter. The cat image data will not be returned until a later time; that time is what requires us to use callback functions to accomplish anything with asynchronous functions. Now, this example may seem trivial, but what happens if you have to call this asynchronous function multiple times? Well, that’s when callback hell or the callback triangle comes in.
Here’s an example.
Promises – How They Solve The Problem
Promises expose a simple way to handle asynchronous functions through the use of then and catch methods. Now, the way it works is that a promise takes a single function with a resolve function and reject function as parameters. When the promise resolves the parameter of the resolve function is passed to the then method. If the promise is rejected, it’s passed to the catch method. Now, one other important feature is that the then method can be called multiple times to transform the result of the promise.
Anyway, the best way to demonstrate is an example, so here’s an example of the original function rewritten with promises.
As you can see, we work through the promise and use then to interact with the values of the promise. You can run this in Node.js and see the data, you can also add more then methods for chaining. This chaining, allows us to create the order we want when working with asynchronous functions.
With that said, that covers the basics of promises, but there are definitely more useful functions. If you have anything to add a comment down below; I’ll gladly answer.