Programming in Amharic

Programming in Amharic

Share

16/10/2023

Promise in JavaScript

Promises in JavaScript are a way to handle asynchronous operations and manage the flow of asynchronous code ex*****on. They provide a cleaner and more structured approach to dealing with callbacks and managing asynchronous tasks.

A promise represents the eventual completion (or failure) of an asynchronous operation and allows you to handle its result. It has three possible states:

Pending: The initial state of a promise when it is neither fulfilled nor rejected.

Fulfilled: The state of a promise when the asynchronous operation completes successfully. The promise is resolved with a value.

Rejected: The state of a promise when the asynchronous operation encounters an error or fails to complete. The promise is rejected with a reason (an error message or an exception).

To create a promise, you use the Promise constructor, which takes a callback function with two parameters: resolve and reject. The callback function represents the asynchronous operation you want to perform. Within the callback function, you call resolve to fulfill the promise with a value, or reject to reject the promise with a reason.

Here's a basic example of creating and using a promise:
et graduate_this_year = false;

let my_graduation = ()=> {
return new Promise((resolve, reject)=>{
setTimeout(()=>{
if(graduate_this_year){
resolve("I will be graduated this year")
}else{
reject("This year, I will not be graduated")
}
}, 5000)
})
}
my_graduation().then((success)=>{
console.log(success)
}).catch((error)=>{
console.log(error)
})

Want your business to be the top-listed Advertising & Marketing Company in Addis Ababa?
Click here to claim your Sponsored Listing.

Website

Address

Addis Ababa
1000