Promise原型對象
在瀏覽器控制檯輸入如下代碼,可以看到Promise原型對象信息。
var p = new Promise(()=>{});
console.log(p)
Promise原型上有catch
、finally
、then
等方法。同時Promise內部維護了兩個屬性值status
和value
Promise構造方法
再看Promise的構造方法,如下圖
構造函數有all
、allSettled
、finally
、race
、reject
、resolve
等方法。
簡單實現
構造函數實現總結:
- 構造函數接受一個函數
executor
,並立即執行; executor
函數接受兩個參數,一個是resolve
函數,一個是rejected
函數,用於後續回調執行;promise
對象的then
方法中的第一個參數(函數)是狀態變爲fulfilled
時的回調。resolve
函數被調用時,會觸發then方法中的回調函數的指定。
const PENDING = 'pending';
const FULFILLED = 'fullfilled';
const REJECTED = 'rejected';
function Promise(executor) {
this.status = PENDING;
this.value = undefined;
this.onResolvedCallback = []; //成功狀態下的回調函數集合
this.onRejectedCallback = [];
function resolve(value) {
};
function reject() {
};
executor(resolve, reject);
}
const PENDING = 'pending';
const FULFILLED = 'fullfilled';
const REJECTED = 'rejected';
function Promise(executor) {
this.status = PENDING;
this.value = undefined;
this.onResolvedCallback = []; //成功狀態下的回調函數集合
this.onRejectedCallback = [];
function resolve(value) {
if(this.status === PENDING) {
this.status = FULFILLED;
this.value = value;
// 觸發後續then方法中的回調方法執行
onRejectedCallback.forEach(onResolved => {
onResolved(value)
});
}
};
function reject() {
};
try { // 考慮到執行executor的過程中有可能出錯,所以我們用try/catch塊給包起來,並且在出錯後以catch到的值reject掉這個Promise
executor(resolve, reject) // 執行executor
} catch(e) {
reject(e)
}
}
``
參考
https://www.jianshu.com/p/b4f0425b22a1
https://github.com/xieranmaya/blog/issues/3