DEV Community

Boluwatife
Boluwatife

Posted on

What's a promise in JavaScript

Promise is an object that manages/handling asynchronous operation.
How promises work.

  1. A promise start in a "pending"state when the asynchronous operation begins.
  2. When the task finishes: it resolves or rejected.
  3. You use: .then () to handle the result if the promise is resolved (success). .catch () to handle the result if the promise is rejected (error).

How to use promise:
My promise.then(value) {/code if successful/}
. catch (object) {/code if some error/}

SYNTAX FOR PROMISE
const promise=new promise ((resolve, reject)=>{
//Simulate an asynchronous operation.
Set timeout (()={
resolved ("Task successful");//fulfilled state
} Else {
rejected ("Task failed");//an error state
},2000);
});
promise
. then ((result)=>console.log(result))
. catch ((error)=>console.log(error));
The "resolve" and "reject" ae not keywords. You can use any name that you want to give to a function.

EXAMPLE: Check if a number is even.

Let checkEven=new promise ((resolve, reject)=>{
let number=6
if (number %2 ==0){
Resolve ("The number is even");
} else{
Reject ("The number is odd");}
});
checkEven
.then((message)=>console.log(message))
.catch((error)=>console.log(error));

Top comments (0)