Tất cả các handler methods của một promise đều trả về một Promise
mới. Do vậy mà chúng ta có thể gọi then
, catch
và finally
liên tiếp nhau.
const promise = new Promise(resolve => resolve(1))
promise
.then((result) => result)
.then((data) => {
console.log(data) // 1
return data + 1
})
.then((data) => {
console.log(data) // 2
return data + 1
})
.then((data) => {
console.log(data) // 3
})
.catch((error) => console.log(error))
.finally(() => console.log('Done')) // Done
Giá trị trả về của handler method trước sẽ là đối số của handler method tiếp theo. Cứ như vậy các handler methods nối liền nhau tạo nên promise chain.
Xét ví dụ sau, phương thức xử lý then
đầu tiên trả về một promise, ta gọi promise này là newPromise
.
promise.then(() => {
return new Promise((resolve) => {
setTimeout(() => {
resolve('Promise is fulfilled')
}, 1000)
})
})
Executor được thực hiện trước khi newPromise
được tạo ra (xem thêm Promise). Mà executor sử dụng hàm setTimeout
để thực thi resolve
. Do đó, chương trình sẽ phải đợi một giây rồi newPromise
mới được chuyển sang trạng thái fulfilled
.
Khi đối tượng newPromise
được trả về, lời gọi phương thức then
thứ hai sẽ gọi thực hiện cho newPromise
.
promise
.then(() => {
return new Promise((resolve) => {
setTimeout(() => {
resolve('Promise is fulfilled')
}, 1000)
})
})
.then((result) => console.log(result)) // Promise is fulfilled
Xét trường hợp khác, giả sử trong các lời gọi phương thức then
, promise trả về có trạng thái rejected
. Lúc này thì nó sẽ nhảy thẳng xuống catch
và bỏ qua các lời gọi then
liền kề.
promise
.then(() => {
return new Promise((resolve, reject) => {
setTimeout(() => {
reject('Promise is rejected')
}, 1000)
})
})
.then((result) => console.log(result))
.catch((error) => console.log(error)) // Promise is rejected
Related
table tags as Tags, file.cday as Created
from [[Promise Chain]]
sort file.ctime asc