DEV Community

Aishanii
Aishanii

Posted on

Promises in javascript(πŸ”–)

Promise is an object that bundles a provider and consumer. To understand this, remember how this keyword was encountered in async javascript blog?

Promises are used to keep track of whether a successful output was received from a piece of code or not.

Promises has two callbacks, either one of which is executed depending on the output received- resolve(value) & reject(error).

Resolve is for successful run while reject is for errors received.

const MyPromise=new Promise((resolve, reject)=>{
    const rand=Math.floor(Math.random()*2);
    console.log(rand)
    if(rand===0)
        resolve();
    else
        reject()

})

MyPromise
.then(()=>{console.log("success")})
.catch(()=>{console.log("Error")})

Enter fullscreen mode Exit fullscreen mode

Image description

Here we are working with a random number case, where it either returns 1 or 2. .then handles succesful responses and .catch works with errors. These are used to access internal Promise properties called state and result.

  • state indicates status of the job that needs to be done. Pending, fulfilled or rejected are the three indicators.

  • result is initially empty but gets a value when either resolved or an error when rejected.

Only the first call to resolve/reject is taken and once the value for state and result is set it's final. More on promises by javascript.info

⭐New to Javascript? Try out great courses from https://boot.dev/tracks/computer-science

Latest comments (2)

Collapse
 
zhaohuolong profile image
zhao-huo-long

your Promise params position is reverse

Collapse
 
aishanipach profile image
Aishanii

Corrected, thanks!