09/11/2018, 23:45

Promise trong Javascript

Vậy promise sinh ra để xử lý kết quả của một hành động cụ thể, kết quả của mỗi hành động sẽ là thành công hoặc thất bại và Promise sẽ giúp chúng ta giải quyết câu hỏi "Nếu thành công thì làm gì? Nếu thất bại thì làm gì?". Cả hai câu hỏi này ta gọi là một hành động gọi lại (callback ...

Promise trong Javascript

Khi một Promise khởi tạo thì có một trong ba trạng thái sau: 

- Fulfilled Hành động xử lý xong và thành công

- Rejected Hành động xử lý xong và thất bại

- Pending Hành động đang chờ xử lý hoặc bị từ chối

Trong đó hai trạng thái Reject và Fulfilled ta gọi là Settled, tức là đã xử lý xong.

 * Tạo Promise:

Cú pháp:

var promise = new Promise(callback);

Trong đó callback là một function có hai tham số truyền vào như sau:

var promise = new Promise(function(resolve, reject){


// resolve là một hàm callback xử lý cho hành động thành công.
// reject là một hàm callback xử lý cho hành động thất bại.
     
});

* Thenable trong Promise:

Thenable không có gì to tác mà nó là một phương thức ghi nhận kết quả của trạng thái (thành công hoặc thất bại) mà ta khai báo ở Reject và Resolve. Nó có hai tham số truyền vào là 2 callback function. Tham số thứ nhất xử lý cho Resolve và tham số thứ 2 xử lý cho Reject.

var promise = new Promise(function(resolve, reject){
    resolve('Success');
    // OR
    reject('Error');
});
 
 
promise.then(
        function(success){
            // Success
        }, 
        function(error){
            // Error
        }
);

VD: với resolve 

var promise = new Promise(function(resolve, reject){
    resolve('Success!');
});
 
 
promise.then(
    function(success){
        console.log(success);
    }
); // Success!

VD: với reject

var promise = new Promise(function(resolve, reject){
    reject('Error!');
});
 
 
promise.then(
    function(success){
        console.log(success);
    },
    function(error){
        console.log(error);
    }
); 
// => Error!

Vậy hai hàm callback trong then chỉ xảy ra một trong hai mà thôi, điều này tương ứng ở Promise sẽ khai báo một là Resolve và hai là Reject, nếu khai báo cả hai thì nó chỉ có tác dụng với khai báo đầu tiên.

var promise = new Promise(function(resolve, reject){
    reject('Error!');
    resolve('Success!');
});
 
 
promise.then(
    function(success){
        console.log(success);
    },
    function(error){
        console.log(error);
    }
);
// kết quả là Error!

* Catch trong Promise


Cú pháp:

	
promise.then().catch();

VD: 

var promise = new Promise(function(resolve, reject){
    reject('Error!');
});
 
 
promise
        .then(function(message){
            console.log(message);
        })
        .catch(function(message){
            console.log(message);
        });
// chạy vào catch => Error!

Nếu ta vừa truyền callback error và vừa sử dụng catch thì thế nào? Câu trả lời nó sẽ chạy hàm callback error và catch sẽ không chạy.

var promise = new Promise(function(resolve, reject){
    reject('Error!');
});
 
 
promise
        .then(function(message){
            console.log(message);
        }, function(message){
            console.log('Callback Error!');
            console.log(message);
        })
        .catch(function(message){
            console.log('Catch!');
            console.log(message);
        });

Trường hợp 1: Nếu trong phương thức then() nào đó có sử dụng callback function Reject thì các phương thức then() ở phía sau sẽ là một Fulfilled, nghĩa là nó sẽ chạy ở callback function Resolve.

VD:

var promise = new Promise(function(resolve, reject){
    reject();
});
 
promise.then(function(){
            console.log(1);
        })
        .then(function(){
            console.log(2);
        }, function(){
            console.log('Error!')
        })
        .then(function(){
            console.log(3);
        });

// => kết quả là Error! , 3

Trường hợp 2: Bạn sử dụng catch để bắt lỗi, lúc này chỉ có phương thức catch() là hoạt động.

var promise = new Promise(function(resolve, reject){
    reject();
});
 
promise.then(function(){
            console.log(1);
        })
        .then(function(){
            console.log(2);
        })
        .then(function(){
            console.log(3);
        })
        .catch(function(){
            console.log('Error!')
        });

// => kết quả là Error!

* Khi sử dụng thenable liên tiếp thì kết quả return của phương thức then() hiện tại sẽ quyết định trạng thái của phương thức  then() tiếp theo. Ví dụ then() phía trên return về một Promise Rejected thì then() phía dưới sẽ nhận một trang thái Rejected.

VD:

var promise = new Promise(function(resolve, reject){
    resolve();
});
 
promise
    .then(function(){
        return new Promise(function(resolve, reject){
            reject();
        });
    })
    .then(function(){
        console.log('Success!');
    })
    .catch(function(){
        console.log('Error!');
    });
// => kết quả là Error!

Việc hiểu nguyên tắc hoạt động của Promise rất quan trọng, nếu  không bạn sẽ rất dễ mắc phải các lỗi về Callback Hell  đấy. ^_^

 

+1