DEV Community

Sambit Kumar Nandađź‘ľ
Sambit Kumar Nandađź‘ľ

Posted on

What is a promise in JavaScript ?

Promises are used to handle asynchronous tasks in JavaScript. Managing them is easier when dealing with multiple asynchronous operations, where we’ll get stuck in callback hell, created by callbacks which ultimately leads to unmanageable code. A Promise is a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers with an asynchronous action's eventual success value or failure reason. A promise is always in one of these states:

â—Ź Pending
â—Ź Resolved
â—Ź Rejected
Creating Promises
We can create a promise using the promise constructor:

const promise = new Promise((resolve,reject) => {
resolve(1)
})

Enter fullscreen mode Exit fullscreen mode

Promise constructor takes a function as a single argument, which takes two arguments, resolve and reject. We will call resolve if everything inside the function goes well, else we call reject. A pending promise can be resolved by providing a value or rejected by providing a reason (error). If any of these options occur, we must take the appropriate steps. The methods promise.then() and promise.catch() are used to take any further action with a promise that becomes settled.

then():
When a promise is resolved or rejected, then() is called. Two functions are passed to the then() method. If the promise is resolved and a result is received, the first function is called. If the promise is rejected and an error is returned, the second function is called. (It's optional as the catch() method is comparatively a better way to handle errors.)

Example:

promise.then((data) => {
// On Resolved
}, (error) => {
// On Rejected
})

Enter fullscreen mode Exit fullscreen mode

catch():
catch() is called to handle the errors, i.e., when a promise is rejected or when some error has occurred during the execution. catch() method takes one function as an argument, which is used to handle errors.
Example:

promise.catch((error) => {
// Handle Error on Rejected or caught Error
})

Enter fullscreen mode Exit fullscreen mode

Top comments (0)