概述
Promise 對象是 JavaScript 的異步操作解決方案,為異步操作提供統一接口。它起到代理作用(proxy),充當異步操作與回調函數之間的中介,使得異步操作具備同步操作的接口。
首先,Promise 是一個對象,也是一個構造函數。
function f1(resolve, reject) {
// 異步代碼...
}
var p1 = new Promise(f1);
上面代碼中,Promise構造函數接受一個回調函數f1作為參數,f1里面是異步操作的代碼。然后,返回的p1就是一個 Promise 實例。
Promise 的設計思想是,所有異步任務都返回一個 Promise 實例。Promise 實例有一個then方法,用來指定下一步的回調函數。
var p1 = new Promise(f1);
p1.then(f2);
上面代碼中,f1的異步操作執行完成,就會執行f2。
Promise 對象的狀態
Promise 對象通過自身的狀態,來控制異步操作。Promise 實例具有三種狀態。
異步操作未完成(pending)
異步操作成功(fulfilled)
異步操作失敗(rejected)
上面三種狀態里面,fulfilled和rejected合在一起稱為resolved(已定型)。
一旦狀態發生變化,就凝固了,不會再有新的狀態變化。
Promise 構造函數
JavaScript 提供原生的Promise構造函數,用來生成 Promise 實例。
var promise = new Promise(function (resolve, reject) {
// ...
if (/* 異步操作成功 */){
resolve(value);
} else { /* 異步操作失敗 */
reject(new Error());
}
});
上面代碼中,Promise構造函數接受一個函數作為參數,該函數的兩個參數分別是resolve和reject。它們是兩個函數,由 JavaScript 引擎提供,不用自己實現。
resolve函數的作用是,將Promise實例的狀態從“未完成”變為“成功”(即從pending變為fulfilled),在異步操作成功時調用,并將異步操作的結果,作為參數傳遞出去。reject函數的作用是,將Promise實例的狀態從“未完成”變為“失敗”(即從pending變為rejected),在異步操作失敗時調用,并將異步操作報出的錯誤,作為參數傳遞出去。
Promise.prototype.then()
Promise 實例的then方法,用來添加回調函數。
then方法可以接受兩個回調函數,第一個是異步操作成功時(變為fulfilled狀態)的回調函數,第二個是異步操作失敗(變為rejected)時的回調函數(該參數可以省略)。一旦狀態改變,就調用相應的回調函數。
var p1 = new Promise(function (resolve, reject) {
resolve('成功');
});
p1.then(console.log, console.error);
// "成功"
var p2 = new Promise(function (resolve, reject) {
reject(new Error('失敗'));
});
p2.then(console.log, console.error);
// Error: 失敗
上面代碼中,p1和p2都是Promise 實例,它們的then方法綁定兩個回調函數:成功時的回調函數console.log,失敗時的回調函數console.error(可以省略)。p1的狀態變為成功,p2的狀態變為失敗,對應的回調函數會收到異步操作傳回的值,然后在控制臺輸出。
then方法可以鏈式使用。
p1
.then(step1)
.then(step2)
.then(step3)
.then(
console.log,
console.error
);
上面代碼中,p1后面有四個then,意味依次有四個回調函數。只要前一步的狀態變為fulfilled,就會依次執行緊跟在后面的回調函數。
最后一個then方法,回調函數是console.log和console.error,用法上有一點重要的區別。console.log只顯示step3的返回值,而console.error可以顯示p1、step1、step2、step3之中任意一個發生的錯誤。舉例來說,如果step1的狀態變為rejected,那么step2和step3都不會執行了(因為它們是resolved的回調函數)。Promise 開始尋找,接下來第一個為rejected的回調函數,在上面代碼中是console.error。這就是說,Promise 對象的報錯具有傳遞性。
Promise 新建后就會立即執行。
let promise = new Promise(function(resolve, reject) {
console.log('Promise');
resolve();
});
promise.then(function() {
console.log('resolved.');
});
console.log('Hi!');
// Promise
// Hi!
// resolved
注意,調用resolve或reject并不會終結 Promise 的參數函數的執行。
new Promise((resolve, reject) => {
resolve(1);
console.log(2);
}).then(r => {
console.log(r);
});
// 2
// 1
一般來說,調用resolve或reject以后,Promise 的使命就完成了,后繼操作應該放到then方法里面,而不應該直接寫在resolve或reject的后面。所以,最好在它們前面加上return語句,這樣就不會有意外。
new Promise((resolve, reject) => {
return resolve(1);
// 后面的語句不會執行
console.log(2);
})
then() 用法辨析
看下面四種寫法,它們的差別在哪里?
// 寫法一
f1().then(function () {
return f2();
});
// 寫法二
f1().then(function () {
f2();
});
// 寫法三
f1().then(f2());
// 寫法四
f1().then(f2);
為了便于講解,下面這四種寫法都再用then方法接一個回調函數f3。
var f1 = new Promise(function (resolve, reject) {
resolve('func1成功');
});
var f2 = function(e) {
console.log('f2', e);
return 'func2';
}
var f3 = function(e) {
console.log('f3', e);
return 'func3';
}
f1.then(function fn(e) {
console.log('fn', e);
return f2();
}).then(f3);
結果:
[Log] fn – "func1成功"
[Log] f2 – undefined
[Log] f3 – "func2"
< Promise = $1
result: "func3"
status: "resolved"
“Promise”原型
結論:
fn回調函數的參數,是Promise 實例f1的運行結果; f3回調函數的參數,是f2函數的運行結果。
f1.then(function fn(e) {
console.log('fn', e);
f2();
}).then(f3);
結果:
[Log] fn – "func1成功"
[Log] f2 – undefined
[Log] f3 – undefined
< Promise = $2
result: "func3"
status: "resolved"
“Promise”原型
結論:
fn回調函數的參數,是Promise 實例f1的運行結果。
f1.then(f2())
.then(f3);
結果:
[Log] f2 – undefined
[Log] f3 – "func1成功"
< Promise = $3
result: "func3"
status: "resolved"
“Promise”原型
結論:
第一個then方法的參數是f2函數的結果'func2';f3回調函數的參數,是Promise 實例f1的運行結果。
f1.then(f2)
.then(f3);
結果:
[Log] f2 – "func1成功"
[Log] f3 – "func2"
< Promise = $5
result: "func3"
status: "resolved"
“Promise”原型
結論:
f2會接收到Promise 實例f1返回的結果, f3回調函數的參數,是f2函數的運行結果。
微任務
Promise 的回調函數屬于異步任務,會在同步任務之后執行。
new Promise(function (resolve, reject) {
resolve(1);
}).then(console.log);
console.log(2);
// 2
// 1
上面代碼會先輸出2,再輸出1。因為console.log(2)是同步任務,而then的回調函數屬于異步任務,一定晚于同步任務執行。
但是,Promise 的回調函數不是正常的異步任務,而是微任務(microtask)。它們的區別在于,正常任務追加到下一輪事件循環,微任務追加到本輪事件循環。這意味著,微任務的執行時間一定早于正常任務。
setTimeout(function() {
console.log(1);
}, 0);
new Promise(function (resolve, reject) {
resolve(2);
}).then(console.log);
console.log(3);
// 3
// 2
// 1
上面代碼的輸出結果是321。這說明then的回調函數的執行時間,早于setTimeout(fn, 0)。因為then是本輪事件循環執行,setTimeout(fn, 0)在下一輪事件循環開始時執行。
Promise.prototype.catch()
用于指定發生錯誤時的回調函數。
const promise = new Promise(function(resolve, reject) {
if(/*異步操作成功*/) {
resolve(res)
} else {
reject(new Error('test'));
}
});
promise.then(res => {
console.log(res);
}).catch(error => {
console.log('error=>', error);
});
一般來說,不要在then方法里面定義 Reject 狀態的回調函數(即then的第二個參數),總是使用catch方法。
// bad
promise
.then(function(data) {
// success
}, function(err) {
// error
});
// good
promise
.then(function(data) { //cb
// success
})
.catch(function(err) {
// error
});
Promise.prototype.finally()
finally方法用于指定不管 Promise 對象最后狀態如何,都會執行的操作。該方法是 ES2018 引入標準的。
promise
.then(result => {···})
.catch(error => {···})
.finally(() => {···});
上面代碼中,不管promise最后的狀態,在執行完then或catch指定的回調函數以后,都會執行finally方法指定的回調函數。
Promise.all()
Promise.all方法用于將多個 Promise 實例,包裝成一個新的 Promise 實例。
const p = Promise.all([p1, p2, p3]);
上面代碼中,Promise.all方法接受一個數組作為參數,p1、p2、p3都是 Promise 實例,如果不是,就會先調用下面講到的Promise.resolve方法,將參數轉為 Promise 實例,再進一步處理。(Promise.all方法的參數可以不是數組,但必須具有 Iterator 接口,且返回的每個成員都是 Promise 實例。)
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 實例,自己定義了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方法指定的回調函數。
如果p2沒有自己的catch方法,就會調用Promise.all()的catch方法。
const p1 = new Promise((resolve, reject) => {
resolve('hello');
})
.then(result => result);
const p2 = new Promise((resolve, reject) => {
throw new Error('報錯了');
})
.then(result => result);
Promise.all([p1, p2])
.then(result => console.log(result))
.catch(e => console.log(e));
// Error: 報錯了
Promise.race()
Promise.race方法同樣是將多個 Promise 實例,包裝成一個新的 Promise 實例。
const 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(console.log)
.catch(console.error);
上面代碼中,如果 5 秒之內fetch方法無法返回結果,變量p的狀態就會變為rejected,從而觸發catch方法指定的回調函數。