對(duì)象的擴(kuò)展
Promise對(duì)象
含義
獲取異步操作的消息,提供統(tǒng)一的API特點(diǎn)
1)對(duì)象的狀態(tài)不受外界影響瘦赫,有三種狀態(tài):Pending(進(jìn)行中)辰晕、Resolved(已完成,又稱 Fulfilled)和Rejected(已失斎肥)含友。只有異步操作的結(jié)果,可以決定當(dāng)前是哪一種狀態(tài)校辩,任何其他操作都無(wú)法改變這個(gè)狀態(tài)窘问。
2)Promise對(duì)象的狀態(tài)改變,只有兩種可能:從Pending變?yōu)镽esolved和從Pending變?yōu)镽ejected宜咒。一旦狀態(tài)改變惠赫,就不會(huì)再變,任何時(shí)候都可以得到這個(gè)結(jié)果
- 基本用法
Promise對(duì)象是一個(gè)構(gòu)造函數(shù)
第一步:創(chuàng)建Promise實(shí)例
var promise = new Promise(function(resolve, reject) {
// ... some code
if (/* 異步操作成功 */){
resolve(value);
} else {
reject(error);
}
});
第二步:Promise實(shí)例生成以后故黑,可以用then方法分別指定Resolved狀態(tài)和Reject狀態(tài)的回調(diào)函數(shù)汉形。
promise.then(function(value) {
// success
}, function(error) {
// failure
});
第三步:then方法的鏈?zhǔn)秸{(diào)用, 用來(lái)添加狀態(tài)改變時(shí)的回調(diào)函數(shù)
getJSON("/post/1.json").then(
post => getJSON(post.commentURL)
).then(
comments => console.log("Resolved: ", comments),
err => console.log("Rejected: ", err)
);
第四步:添加catch()方法倍阐,用于指定發(fā)生錯(cuò)誤時(shí)的回調(diào)函數(shù)。
getJSON('/posts.json').then(function(posts) {
// ...
}).catch(function(error) {
// 處理 getJSON 和 前一個(gè)回調(diào)函數(shù)運(yùn)行時(shí)發(fā)生的錯(cuò)誤
console.log('發(fā)生錯(cuò)誤逗威!', error);
});
Promise 對(duì)象的錯(cuò)誤具有“冒泡”性質(zhì)峰搪,會(huì)一直向后傳遞,直到被捕獲為止凯旭。也就是說(shuō)概耻,錯(cuò)誤總是會(huì)被下一個(gè)catch語(yǔ)句捕獲。
getJSON('/post/1.json').then(function(post) {
return getJSON(post.commentURL);
}).then(function(comments) {
// some code
}).catch(function(error) {
// 處理前面三個(gè)Promise產(chǎn)生的錯(cuò)誤
});
一般來(lái)說(shuō)罐呼,不要在then方法里面定義Reject狀態(tài)的回調(diào)函數(shù)(即then的第二個(gè)參數(shù))鞠柄,總是使用catch方法。
// bad
promise
.then(function(data) {
// success
}, function(err) {
// error
});
// good
promise
.then(function(data) { //cb
// success
})
.catch(function(err) {
// error
});