JavaScript Promises Explained
The introduction of promises in ES6 was released to help work with callbacks. There is a term called, “callback hell”, that refers to a situation where you have nested callbacks to the point that it affects the readability of your code.
A JavaScript promise is an object that can be returned synchronously after the completion of a chain of asynchronous tasks. There are three states that the object can be in when returned.
- Pending: This is a state where the promise hasn’t returned a final value yet and can be transitioned into one of the other two states.
- Rejected: This state is where an error has been thrown and the task has failed.
- Fulfilled: This state is where the tasks have thrown zero errors and have completed successfully.
Out of these three states, both the rejected and fulfilled states are considered settled because it’s no in a pending state where you’re returned an error or completion of the task.
Now that you have a better understanding of a promise, we can look into what it can do to help with the readability of your code.
The example below shows what a nested callback looks like and can be hard to read and even harder to manage.
demoFunction(args, function() {
firstFunction(args, function() {
secondFunction(args, function() {
thirdFunction(args, function() {
});
});
});
});
With promises, you can use a .then() to chain them together instead of nested callbacks.
demoFunction()
.then((args) => firstFunction(args))
.then((args) => secondFunction(args))
.then((args) => thirdFunction(args))
The .then promise chains help clean up the code and allow for easier readability.