Asynchronous JavaScript Promises

Handling state changes

We can wait for a Promise to either settle (fulfill or fail) by using the then and catch methods.

fetch("/abc")
.then(value => {
console.log("the Promise was resolved with the value:", value)
})
.catch(error => {
console.log("the Promise was rejected with the error:", error)
})

Here fetch is some method or function that returns a Promise. We can use the then method to specify which function should run after the Promise have resolved. The catch method is used to specify which function should run after the Promise have failed.

Chaining

We can chain as many then and catch methods in a chain as we want, as these methods themselves return new promises. The chain of promises are nested like Russian dolls, and are executed from top to bottom.

It is usually a good idea to have a single catch for the entire chain, as it makes error handling and debugging simpler.

returnsPromiseFn(arg1, arg2)
.then(value => returnsPromiseFn2())
.then(value => returnsPromiseFn3())
.then(value => returnsPromiseFn4())
.then(value => 2)
.catch(error => {
console.log("the Promise was rejected with the error:", error)
})

Read more on MDN

Promise