Promise.all is a JavaScript method that allows you to execute multiple asynchronous operations (promises) concurrently. It takes an array of promises and returns a single promise that resolves when all the promises resolve or rejects if any of the promises reject.
Key Features:
- Parallel Execution: Promises run simultaneously, reducing the overall time for execution compared to running them sequentially.
- Result Aggregation: The resolved values of all promises are returned as an array, maintaining the order of the original promises.
- Error Handling: If any promise rejects,
Promise.allimmediately rejects with that error, making it easy to catch and debug issues.
Example:
export default {
data() {
return {
users: null,
posts: null,
error: null,
};
},
methods: {
fetchData() {
const usersPromise = fetch('https://api.example.com/users').then(res => res.json());
const postsPromise = fetch('https://api.example.com/posts').then(res => res.json());
Promise.all([usersPromise, postsPromise])
.then(([users, posts]) => {
this.users = users;
this.posts = posts;
})
.catch((err) => {
this.error = `Error fetching data: ${err.message}`;
});
},
},
mounted() {
this.fetchData();
},
};