Promises in JavaScript

Shawn ConwayShawn Conway
2 min read

A promise handles asynchronous operations in our code. The W3 schools website states that a promise links producing code, which is code that can take some time, to consuming code. Consuming code must wait for results. A promise takes one argument, a callback function. The callback function has two arguments itself. These are resolved and rejected. If the operations in the callback function go well resolved is called. The rejected argument is called when operations fail. Geeks for Geeks website tells us a promise can have four states. These states are fulfilled, rejected, pending, and settled. Fulfilled is the state that the promise's action succeeds. If the promise fails the state is rejected. When a promise has not been fulfilled or rejected yet it is considered pending. Settled is the opposite of pending. The promise has either been fulfilled or rejected. Two types of promise methods that can be used on objects. The first type is the static method. The static method calls using the array class itself. There are six static methods. The first is all(). This handles all asynchronous operations that take an array of promises as input. The allSettled() method will get a promise when all inputs are either fulfilled or rejected. The any() method will return a single promise that fulfills its value. The race() method returns a single promise from an array of promises. The reject() returns rejected objects. The resolve() returns if it is resolved. The second type of method is referred to as an Instance Method. This is called on the instance of a promise. There are three types of instance methods. The .catch() is the return value of the callback. The .then() method deals with asynchronous tasks. The finally() method returns a promise when it is settled, meaning fulfilled or rejected. Promises have two consumers. They can be taken in by functions using .then() and .catch() methods. The .then() method acts as a carrier of data from a promise and executes it successfully. The .catch() is used as an Error Handler whenever an error may appear. The .then() method has two functions in its parameters. The first function is callled if the promise is resolved and the result is received. The second function is optional. This function is called if the promise is rejected and an error is received. Using the .catch() method is a better way of handling errors. The .catch() method has one function that handles errors and promise rejections.

resources:

w3 schools website

geeks for geeks website

0
Subscribe to my newsletter

Read articles from Shawn Conway directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Shawn Conway
Shawn Conway