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

Image of Timescale

šŸš€ pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applicationsā€”without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post ā†’

Top comments (2)

Collapse
 
zhaohuolong profile image
zhao-huo-long ā€¢

your Promise params position is reverse

Collapse
 
aishanipach profile image
Aishanii ā€¢

Corrected, thanks!

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more