Đối tượng hứa hẹn JavaScript
Đối tượng Promise thể hiện sự hoàn thành hoặc thất bại của một hoạt động không đồng bộ và kết quả của nó.
Một Promise có thể có 3 trạng thái:
chưa giải quyết | trạng thái ban đầu |
vật bị loại bỏ | lỗi hệ thống |
hoàn thành | hoạt động hoàn thành |
Ví dụ
// Create a Promise Object
let myPromise = new Promise(function(myResolve, myReject) {
let result = true;
// Code that may take some time goes here
if (result == true) {
myResolve("OK");
} else {
myReject("Error");
}
});
// Using then() to display result
myPromise.then(x => myDisplay(x), x => myDisplay(x));
Các phương thức và thuộc tính hứa hẹn của JavaScript
Name | Description |
---|---|
Promise.all() | Returns a single Promise from a list of promises When all promises fulfill |
Promise.allSettled() | Returns a single Promise from a list of promises When all promises sette |
Promise.any() | Returns a single Promise from a list of promises When any promise fulfills |
Promise.race() | Returns a single Promise from a list of promises When the faster promise settles |
Promise.reject() | Returns a Promise object rejected with a value |
Promise.resolve() | Returns a Promise object resolved with a value |
catch() | Provides a function to be called when a promise is rejected |
finally() | Provides a function to be called when a promise is fulfilled or rejected |
then() | Provide two functions to be called when a promise is fulfilled or rejected |