Promise is an important and powerful concept for handling asynchronous tasks.
Promise helps us create sequential processing chains, handle errors easier, and increase the stability of the application. It can have 3 states:
Promise can be seen as a contract between the sender and the receiver. The sender makes a promise and the receiver will receive the result after the task is completed.
To create a Promise in JavaScript, we use the Promise constructor with the following syntax:
const promise = new Promise((resolve, reject) => {
// Code xử lý tác vụ bất đồng bộ
});
In the Promise constructor, we pass a function with two parameters: resolve and reject. resolve is used to return a successful result and reject is used to return an error.
After creating a Promise, we can use the .then() and .catch() methods to handle the result or error of the Promise.
The .then() method is used to handle the successful result of a Promise. For example:
promise.then((result) => {
// Xử lý kết quả thành công
}).catch((error) => {
// Xử lý lỗi
});
The .catch() method is used to handle errors of a Promise. If an error occurs during the processing of the Promise, the .catch() method will be called.
Here is a simple example of how to use Promise in JavaScript:
const fetchData = (url) => {
return new Promise((resolve, reject) => {
// Mô phỏng việc gửi request tới server
setTimeout(() => {
const data = { name: "John Doe", age: 25 };
resolve(data);
}, 2000);
});
};
fetchData("https://api.example.com/users")
.then((data) => {
console.log(data);
})
.catch((error) => {
console.error(error);
});
In the example above, the fetchData function returns a Promise and simulates sending a request to the server. After the task is completed, the Promise will return the data and we can use the .then() method to handle the successful result. If an error occurs, the .catch() method will be called to handle the error.
Promise.all is a method of the Promise object in JavaScript. It allows you to handle an array of promises at the same time and wait for all the promises to complete before continuing with other tasks.
Refer to the following example:
// Tạo một hàm trả về promise với thời gian chờ
function delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
// Tạo một mảng chứa các promise
const promises = [
delay(1000).then(() => "Promise 1 hoàn thành"),
delay(2000).then(() => "Promise 2 hoàn thành"),
delay(3000).then(() => "Promise 3 hoàn thành"),
];
// Sử dụng Promise.all để xử lý các promise
Promise.all(promises)
.then((results) => {
console.log(results);
// Kết quả: ["Promise 1 hoàn thành", "Promise 2 hoàn thành", "Promise 3 hoàn thành"]
})
.catch((error) => {
console.log(error);
});
In the example above, we create a function delay that returns a promise with the specified wait time. Then, we create an array promises containing three promises with different wait times. Finally, we use Promise.all to handle all the promises in the promises array and wait for all of them to complete.
The result of Promise.all will return an array of results of the promises resolved in the original order. In the example above, the result will be an array containing three strings "Promise 1 completed", "Promise 2 completed", and "Promise 3 completed".