Js Promise
Before learning this chapter, you need to understand what asynchronous programming is. You can refer to: (#)
Promise is a class provided by ECMAScript 6, designed to write complex asynchronous tasks more elegantly.
Promise is an object in JavaScript used to handle asynchronous operations. It represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
Simply put, Promise is a "commitment" that indicates that at some point in the future, it will return a result (either a successful result or a reason for failure).
Promise has three states:
* pending: initial state, neither successful nor failed
* fulfilled: means the operation completed successfully
* rejected: means the operation failed
!(#)
## Example
const myPromise =new Promise((resolve, reject)=>{
// Asynchronous operation code
if(/* operation successful */){
resolve('successful result');// Change Promise state to fulfilled
}else{
reject('failure reason');// Change Promise state to rejected
}
});
### Browser Support
Since Promise is a new feature added in ES6, some older browsers do not support it. Apple's Safari 10 and Windows Edge 14 and above versions started supporting ES6 features.
The following is the browser support for Promise:
| | | | | |
| --- | --- | --- | --- | --- |
| Chrome 58 | Edge 14 | Firefox 54 | Safari 10 | Opera 55 |
* * *
## How to Use Promise
### then() Method
The `then()` method is used to specify callback functions when the Promise state becomes fulfilled or rejected.
## Example
myPromise.then(
(result)=>{
// Handle success scenario
console.log('Success:', result);
},
(error)=>{
// Handle failure scenario
console.error('Failure:', error);
}
);
### catch() Method
The `catch()` method is specifically used to handle Promise rejection scenarios.
## Example
myPromise
.then((result)=>{
console.log('Success:', result);
})
.catch((error)=>{
console.error('Failure:', error);
});
### finally() Method
The `finally()` method executes regardless of the final state of the Promise.
## Example
myPromise
.then((result)=>{
console.log('Success:', result);
})
.catch((error)=>{
console.error('Failure:', error);
})
.finally(()=>{
console.log('Operation completed');
});
* * *
## Promise Chaining
A powerful feature of Promise is the ability to chain multiple asynchronous operations.
## Example
doFirstThing()
.then((result)=> doSecondThing(result))
.then((newResult)=> doThirdThing(newResult))
.then((finalResult)=>{
console.log('Final result:', finalResult);
})
.catch((error)=>{
console.error('Error somewhere in the chain:', error);
});
* * *
## Promise Static Methods
### Promise.all()
Waits for all Promises to complete, or for any one Promise to fail.
## Example
Promise.all([promise1, promise2, promise3])
.then((results)=>{
// results is an array containing all Promise results
console.log(results);
})
.catch((error)=>{
// Enter here if any Promise fails
console.error(error);
});
### Promise.race()
Returns the result of the Promise that completes first (whether successful or failed).
## Example
Promise.race([promise1, promise2, promise3])
.then((result)=>{
// Use the result of the first completed Promise
console.log(result);
})
.catch((error)=>{
// If the first completed Promise is failed
console.error(error);
});
### Promise.resolve() and Promise.reject()
Quickly create a resolved or rejected Promise.
## Example
const resolvedPromise = Promise.resolve('immediately resolved value');
const rejectedPromise = Promise.reject('immediately rejected reason');
* * *
## Practical Application Examples
### Example 1: Using Promise to Handle AJAX Requests
## Example
function fetchData(url){
return new Promise((resolve, reject)=>{
const xhr =new XMLHttpRequest();
xhr.open('GET', url);
xhr.onload=()=>{
if(xhr.status===200){
resolve(xhr.response);
}else{
reject(new Error(xhr.statusText));
}
};
xhr.onerror=()=> reject(new Error('Network error'));
xhr.send();
});
}
fetchData('https://api.example.com/data')
.then((data)=>{
console.log('Data fetched successfully:', data);
})
.catch((error)=>{
console.error('Failed to fetch data:', error);
});
### Example 2: Using Promise Chain to Handle Multiple Asynchronous Operations
## Example
function getUser(userId){
return fetch(`/users/${userId}`);
}
function getPosts(userId){
return fetch(`/users/${userId}/posts`);
}
getUser(123)
.then((user)=>{
console.log('User info fetched:', user);
return getPosts(user.id);
})
.then((posts)=>{
console.log('User posts fetched:', posts);
})
.catch((error)=>{
console.error('Operation failed:', error);
});
* * *
## Common Questions and Best Practices
### 1. Avoid Promise Nesting
Wrong approach (Promise version of callback hell):
## Example
doFirstThing().then((firstResult)=>{
doSecondThing(firstResult).then((secondResult)=>{
doThirdThing(secondResult).then((thirdResult)=>{
console.log(thirdResult);
});
});
});
Correct approach (using chaining):
## Example
doFirstThing()
.then(doSecondThing)
.then(doThirdThing)
.then((finalResult)=>{
console.log(finalResult);
});
### 2. Always Handle Rejections
Forgetting to handle Promise rejections will lead to "
YouTip