Promises
In JavaScript, promises are a way to handle asynchronous operations. They provide a cleaner and more readable way to manage async code compared to traditional callback functions.
A promise is an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
To create a promise, we use the Promise
constructor and pass a function as an argument. This function takes two parameters: resolve
and reject
.
Here's an example of creating and using a promise:
JAVASCRIPT
1function getData() {
2 return new Promise((resolve, reject) => {
3 setTimeout(() => {
4 const data = [1, 2, 3, 4, 5];
5 resolve(data);
6 }, 2000);
7 });
8}
9
10getData()
11 .then(data => {
12 console.log('Received data:', data);
13 })
14 .catch(error => {
15 console.log('Error occurred:', error);
16 });
xxxxxxxxxx
18
// Promises example
function getData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const data = [1, 2, 3, 4, 5];
resolve(data);
}, 2000);
});
}
getData()
.then(data => {
console.log('Received data:', data);
})
.catch(error => {
console.log('Error occurred:', error);
});
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment