What's Promises in JavaScript?

What's Promises in JavaScript?

let's delve in the promise that annoys a lot of developers.

ยท

2 min read

The promise

it is object represents the finalizing of asynchronous operation whether it's a success or failure with its result, in simple words the promise is a proxy to handle asynchronous operation like fetching data.

As diagram Promise have 3 states:

pending: initial state,

fulfilled: means operation completed successfully,

rejected: means operation failed,

How to use promise?

const myPromise= new Promise(function(fulfilled,rejected){

    //promise operation

    fulfilled(); // when operation succeed 

    rejected(); //when opertion failed

})


//consuming the promise function


myPromise().then(
    function(value){/*the code if successful */},
    function(error){/*the code if error */}
    );

We create our promise function by using Promise constructor and passing in it a callback. This callback is passed two arguments: a resolve callback used to resolve the promise with a value or the result, and a reject callback used to reject the promise with a provided reason or error.

Let's explain it more by example.

const myPromise= new Promise(function(fulfill,reject){

    setTimeout(()=>{

        const rand=Math.random();
        if(rand>.5){
            fulfill('Success');
        }else{
            reject(new Error('Failure'));
        }

                },2000) 
                            });

myPromise.then((value)=>{
    console.log(value);
},
(error)=>{
    console.log(error.message);
});

We create myPromise function by promise object and pass to it two callbacks functions (fulfill, reject) and return rand number every 2 seconds and if the number >0.5 so the operation success and pass a message "Success" to the fulfill callback function, else pass error to reject callback function.

Then we get the result of myPromise function by then function that attaches the resolution or rejection of our promise.

You can get the error of reject function callback by use catch();

myPromise.then((value)=>{
    console.log(value);
}).catch((error)=>{
    console.log(error.message);
})

Chaining in promise:

in promise you can chain promises in each other's like ๐Ÿ‘‡

doSomething()
  .then((result) => doSomethingElse(result))
  .then((newResult) => doThirdThing(newResult))
  .then((finalResult) => console.log(`Got the final result: ${finalResult}`))
  .catch(failureCallback);

here we use the catch in the last step, this function catches any error happened in any previous promise functions.

I hope that I have succeeded in my explanation and thank you, keep in touch @ismailabualmagd

ย