An Interest In:
Web News this Week
- April 18, 2024
- April 17, 2024
- April 16, 2024
- April 15, 2024
- April 14, 2024
- April 13, 2024
- April 12, 2024
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")})
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
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To