DEV Community

Aishanii
Aishanii

Posted on

3

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

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (2)

Collapse
 
zhaohuolong profile image
zhao-huo-long β€’

your Promise params position is reverse

Collapse
 
aishanipach profile image
Aishanii β€’

Corrected, thanks!

The best way to debug slow web pages cover image

The best way to debug slow web pages

Tools like Page Speed Insights and Google Lighthouse are great for providing advice for front end performance issues. But what these tools can’t do, is evaluate performance across your entire stack of distributed services and applications.

Watch video

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay