To create and use JavaScript promises for asynchronous programming, follow these steps:
Promise
constructor to create a new Promise object. The constructor takes a function as an argument, with two parameters: resolve
and reject
. These parameters are functions that you call to either fulfill or reject the Promise. Inside this function, you write the asynchronous code that you want to wrap in a Promise.const myPromise = new Promise((resolve, reject) => {
// Asynchronous code here
});
resolve
function to fulfill the Promise, or the reject
function to reject the Promise. Pass the desired result or error as an argument to these functions.const myPromise = new Promise((resolve, reject) => {
setTimeout(() => {
const randomNum = Math.random();
if (randomNum > 0.5) {
resolve(randomNum);
} else {
reject(new Error('Random number is less than 0.5'));
}
}, 1000);
});
then
method to handle the resolved Promise, and the catch
method to handle the rejected Promise. These methods take a function as an argument, which will be called when the Promise is fulfilled or rejected.myPromise
.then(result => {
console.log('Promise fulfilled:', result);
})
.catch(error => {
console.error('Promise rejected:', error);
});
then
method. This allows you to execute multiple asynchronous operations in sequence.myPromise
.then(result => {
console.log('Promise fulfilled:', result);
return anotherPromise(result);
})
.then(anotherResult => {
console.log('Another Promise fulfilled:', anotherResult);
})
.catch(error => {
console.error('Promise rejected:', error);
});
That's it! You have created and used a JavaScript Promise for asynchronous programming. Promises provide a more elegant way to handle asynchronous operations and avoid callback hell.