(1)Promise 含義
Promise 是異步編程的一種解決方案,是一個對象,從它可以獲取異步操作的消息。簡單說就是一個容器,裡面保存着某個未來才會結束的事件的結果。
Promise對象有以下兩個特點:
(1)對象的狀態不受外界影響。有三種狀態:pending(進行中)、fulfilled(已成功)和rejected(已失敗)。只有異步操作的結果,可以決定當前是哪一種狀態,任何其他操作都無法改變這個狀態。 (2)一旦狀態改變,就不會再變,任何時候都可以得到這個結果。Promise對象的狀態改變,只有兩種可能:從pending變為fulfilled和從pending變為rejected。
Promise缺點:
(1)無法取消Promise,一旦新建它就會立即執行,無法中途取消。 (2)如果不設置回調函數,Promise內部拋出的錯誤,不會反應到外部。 (3)當處於pending狀態時,無法得知目前進展到哪一個階段(剛剛開始還是即將完成)。
注意:後面的resolved統一隻指fulfilled狀態,不包含rejected狀態。
(2)基本用法
ES6 規定,Promise對象是一個構造函數,用來生成Promise實例。
var promise = new Promise(function(resolve, reject) {
// ... some code
if (/* 異步操作成功 */){
resolve(value);
} else {
reject(error);
}
});
Promise構造函數接受一個函數作為參數,該函數的兩個參數分別是resolve和reject。是兩個函數,由 JavaScript 引擎提供,不用自己部署。
resolve函數的作用是,將Promise對象的狀態從“未完成”變為“成功”(即從 pending 變為 resolved),在異步操作成功時調用,並將異步操作的結果,作為參數傳遞出去; reject函數的作用是,將Promise對象的狀態從“未完成”變為“失敗”(即從 pending 變為 rejected),在異步操作失敗時調用,並將異步操作報出的錯誤,作為參數傳遞出去。
Promise實例生成以後,可以用then方法分別指定resolved狀態和rejected狀態的回調函數,rejected函數是可選的,不一定要提供,兩個函數都接受Promise對象傳出的值作為參數。
promise.then(function(value) {
// success
}, function(error) {
// failure
});
注意,調用resolve或reject並不會終結 Promise 的參數函數的執行。
new Promise((resolve, reject) => {
resolve(1);
console.log(2);
}).then(r => {
console.log(r);
});
// 2
// 1
上面代碼中,調用resolve(1)以後,後面的console.log(2)還是會執行,並且會首先打印出來。這是因為立即 resolved 的 Promise 是在本輪事件循環的末尾執行,總是晚於本輪循環的同步任務。
調用resolve或reject以後,Promise 的使命就完成了,後繼操作應該放到then方法裡面,而不應該直接寫在resolve或reject的後面。所以,最好在它們前面加上return語句,這樣就不會有意外。 new Promise((resolve, reject) => { return resolve(1); // 後面的語句不會執行
console.log(2); })
(3)Promise.prototype.then()
Promise 實例具有then方法,也就是說,then方法是定義在原型對象Promise.prototype上的。它的作用是為 Promise 實例添加狀態改變時的回調函數。
then方法返回的是一個新的Promise實例(注意,不是原來那個Promise實例)。因此可以採用鏈式寫法,即then方法後面再調用另一個then方法。
getjson("/post/1.json").then(function(post) {
return getJSON(post.commentURL);
}).then(function funcA(comments) {
console.log("resolved: ", comments);
}, function funcB(err){
console.log("rejected: ", err);
});
上面代碼中,第一個then方法指定的回調函數,返回的是另一個Promise對象。這時,第二個then方法指定的回調函數,就會等待這個新的Promise對象狀態發生變化。如果變為resolved,就調用funcA,如果狀態變為rejected,就調用funcB。
(4)Promise.prototype.catch()
Promise.prototype.catch方法是.then(null, rejection)的別名,用於指定發生錯誤時的回調函數。
getJSON('/posts.json').then(function(posts) {
// ...
}).catch(function(error) {
// 處理 getJSON 和 前一個回調函數運行時發生的錯誤
console.log('發生錯誤!', error);
});
上面代碼中,getJSON方法返回一個 Promise 對象,如果該對象狀態變為resolved,則會調用then方法指定的回調函數;如果異步操作拋出錯誤,狀態就會變為rejected,就會調用catch方法指定的回調函數,處理這個錯誤。另外,then方法指定的回調函數,如果運行中拋出錯誤,也會被catch方法捕獲。
如果Promise狀態已經變成resolved,再拋出錯誤是無效的。
var promise = new Promise(function(resolve, reject) {
resolve('ok');
throw new Error('test');
});
promise
.then(function(value) { console.log(value) })
.catch(function(error) { console.log(error) });
// ok
Promise 對象的錯誤具有“冒泡”性質,會一直向後傳遞,直到被捕獲為止。也就是說,錯誤總是會被下一個catch語句捕獲。
getJSON('/post/1.json').then(function(post) {
return getJSON(post.commentURL);
}).then(function(comments) {
// some code
}).catch(function(error) {
// 處理前面三個Promise產生的錯誤
});
上面代碼中,一共有三個Promise對象:一個由getJSON產生,兩個由then產生。它們之中任何一個拋出的錯誤,都會被最後一個catch捕獲。
不要在then方法裡面定義Reject狀態的回調函數(即then的第二個參數),總是使用catch方法。
// bad
promise
.then(function(data) {
// success
}, function(err) {
// error
});
// good
promise
.then(function(data) { //cb
// success
}).catch(function(err) {
// error
});
上面代碼中,第二種寫法要好於第一種寫法,理由是第二種寫法可以捕獲前面then方法執行中的錯誤,也更接近同步的寫法(try/catch)。因此,建議總是使用catch方法,而不使用then方法的第二個參數。
跟傳統的try/catch代碼塊不同的是,如果沒有使用catch方法指定錯誤處理的回調函數,Promise 對象拋出的錯誤不會傳遞到外層代碼,即不會有任何反應。
const someAsyncThing = function() {
return new Promise(function(resolve, reject) {
// 下面一行會報錯,因為x沒有聲明
resolve(x + 2);
});
};
someAsyncThing().then(function() {
console.log('everything is great');
});
setTimeout(() => { console.log(123) }, 2000);
// Uncaught (in promise) ReferenceError: x is not defined
// 123
上面代碼中,someAsyncThing函數產生的 Promise 對象,內部有語法錯誤。瀏覽器運行到這一行,會打印出錯誤提示ReferenceError: x is not defined,但是不會退出進程、終止腳本執行,2秒之後還是會輸出123。這就是說,Promise 內部的錯誤不會影響到 Promise 外部的代碼,通俗的說法就是“Promise 會吃掉錯誤”。
(5)Promise.all()
Promise.all方法用於將多個 Promise 實例,包裝成一個新的 Promise 實例。 Promise.all方法的參數可以不是數組,但必須具有 Iterator 接口,且返回的每個成員都是 Promise 實例。
var p = Promise.all([p1, p2, p3]);
p的狀態由p1、p2、p3決定,分成兩種情況:
(1)只有p1、p2、p3的狀態都變成fulfilled,p的狀態才會變成fulfilled,此時p1、p2、p3的返回值組成一個數組,傳遞給p的回調函數。
(2)只要p1、p2、p3之中有一個被rejected,p的狀態就變成rejected,此時第一個被reject的實例的返回值,會傳遞給p的回調函數。
// 生成一個Promise對象的數組
var promises = [2, 3, 5, 7, 11, 13].map(function (id) {
return getJSON('/post/' + id + ".json");
});
Promise.all(promises).then(function (posts) {
// ...
}).catch(function(reason){
// ...
});
上面代碼中,promises是包含6個 Promise 實例的數組,只有這6個實例的狀態都變成fulfilled,或者其中有一個變為rejected,才會調用Promise.all方法後面的回調函數。
注意:如果作為參數的 Promise 實例,自己定義了catch方法,那麼它一旦被rejected,並不會觸發Promise.all()的catch方法。
const p1 = new Promise((resolve, reject) => {
resolve('hello');
})
.then(result => result)
.catch(e => e);
const p2 = new Promise((resolve, reject) => {
throw new Error('報錯了');
})
.then(result => result)
.catch(e => e);
Promise.all([p1, p2])
.then(result => console.log(result))
.catch(e => console.log(e));
// ["hello", Error: 報錯了]
上面代碼中,p1會resolved,p2首先會rejected,但是p2有自己的catch方法,該方法返回的是一個新的 Promise 實例,p2指向的實際上是這個實例。該實例執行完catch方法後,也會變成resolved,導致Promise.all()方法參數裡面的兩個實例都會resolved,因此會調用then方法指定的回調函數,而不會調用catch方法指定的回調函數。
(6)Promise.race()
Promise.race方法同樣是將多個Promise實例,包裝成一個新的Promise實例。
var p = Promise.race([p1, p2, p3]);
上面代碼中,只要p1、p2、p3之中有一個實例率先改變狀態,p的狀態就跟着改變。那個率先改變的 Promise 實例的返回值,就傳遞給p的回調函數。
const p = Promise.race([
fetch('/resource-that-may-take-a-while'),
new Promise(function (resolve, reject) {
setTimeout(() => reject(new Error('request timeout')), 5000)
})
]);
p.then(response => console.log(response));
p.catch(error => console.log(error));
上面代碼中,如果5秒之內fetch方法無法返回結果,變量p的狀態就會變為rejected,從而觸發catch方法指定的回調函數。
(7)Promise.resolve()
有時需要將現有對象轉為Promise對象,Promise.resolve方法就起到這個作用。
var jsPromise = Promise.resolve($.ajax('/whatever.json'));
Promise.resolve方法的參數分成四種情況:
(1)參數是一個Promise實例 如果參數是Promise實例,那麼Promise.resolve將不做任何修改、原封不動地返回這個實例。
(2)參數是一個thenable對象 thenable對象指的是具有then方法的對象,比如下面這個對象。
let thenable = {
then: function(resolve, reject) {
resolve(42);
}
};
let p1 = Promise.resolve(thenable);
p1.then(function(value) {
console.log(value); // 42
});
Promise.resolve方法會將這個對象轉為Promise對象,然後就立即執行thenable對象的then方法。then方法執行後,對象p1的狀態就變為resolved,從而立即執行最後那個then方法指定的回調函數,輸出42。
(3)參數不是具有then方法的對象,或根本就不是對象 如果參數是一個原始值,或者是一個不具有then方法的對象,則Promise.resolve方法返回一個新的Promise對象,狀態為resolved。
let thenable = {
then: function(resolve, reject) {
resolve(42);
}
};
let p1 = Promise.resolve(thenable);
p1.then(function(value) {
console.log(value); // 42
});
上面代碼生成一個新的Promise對象的實例p。由於字符串Hello不屬於異步操作(判斷方法是字符串對象不具有then方法),返回Promise實例的狀態從一生成就是resolved,所以回調函數會立即執行。Promise.resolve方法的參數,會同時傳給回調函數。 (4)不帶有任何參數 Promise.resolve方法允許調用時不帶參數,直接返回一個resolved狀態的Promise對象。 所以,如果希望得到一個Promise對象,比較方便的方法就是直接調用Promise.resolve方法。
var p = Promise.resolve();
p.then(function () {
// ...
});
上面代碼的變量p就是一個Promise對象。
注意:立即resolve的Promise對象,是在本輪“事件循環”(event loop)的結束時,而不是在下一輪“事件循環”的開始時。
setTimeout(function () {
console.log('three');
}, 0);
Promise.resolve().then(function () {
console.log('two');
});
console.log('one');
// one
// two
// three
上面代碼中,setTimeout(fn, 0)在下一輪“事件循環”開始時執行,Promise.resolve()在本輪“事件循環”結束時執行,console.log('one')則是立即執行,因此最先輸出。
(8)Promise.reject()
Promise.reject(reason)方法也會返回一個新的 Promise 實例,該實例的狀態為rejected。
var p = Promise.reject('出錯了');
// 等同於
var p = new Promise((resolve, reject) => reject('出錯了'))
p.then(null, function (s) {
console.log(s)
});
// 出錯了
注意:Promise.reject()方法的參數,會原封不動地作為reject的理由,變成後續方法的參數。這一點與Promise.resolve方法不一致。
const thenable = {
then(resolve, reject) {
reject('出錯了');
}
};
Promise.reject(thenable).catch(e => {
console.log(e === thenable)
})
// true
上面代碼中,Promise.reject方法的參數是一個thenable對象,執行以後,後面catch方法的參數不是reject拋出的“出錯了”這個字符串,而是thenable對象。
(9)兩個有用的附加方法
done()
Promise對象的回調鏈,不管以then方法或catch方法結尾,要是最後一個方法拋出錯誤,都有可能無法捕捉到(因為Promise內部的錯誤不會冒泡到全局)。因此,我們可以提供一個done方法,總是處於回調鏈的尾端,保證拋出任何可能出現的錯誤。
asyncFunc()
.then(f1)
.catch(r1)
.then(f2)
.done();
// done的實現代碼
Promise.prototype.done = function (onFulfilled, onRejected) {
this.then(onFulfilled, onRejected)
.catch(function (reason) {
// 拋出一個全局錯誤
setTimeout(() => { throw reason }, 0);
});
};
finally()
finally方法用於指定不管Promise對象最後狀態如何,都會執行的操作。它與done方法的最大區別,它接受一個普通的回調函數作為參數,該函數不管怎樣都必須執行。
server.listen(0)
.then(function () {
// run test
}).finally(server.stop);
(10)Promise.try()
由於Promise.try為所有操作提供了統一的處理機制,所以如果想用then方法管理流程,最好都用Promise.try包裝一下,可以更好地管理異常。
const f = () => console.log('now');
Promise.try(f);
console.log('next');
// now
// next
Promise.try(database.users.get({id: userId}))
.then(...)
.catch(...)
事實上,Promise.try就是模擬try代碼塊,就像promise.catch模擬的是catch代碼塊。