Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
July 14, 2022 07:24 am GMT

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((reject, resolve)=>{    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")})

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


Original Link: https://dev.to/aishanipach/promises-in-javascript-4d6c

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To