David Yu Blog

建構子函數 當函數是參數

Word count: 244Reading time: 1 min
2023/04/27

在研究JS的Promise時,對這種寫法感到陌生

1
2
3
4
5
const promise1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('foo');
}, 300);
});

不太能理解,傳參是function,裡頭的參數又有兩個function,然後裡面再去執行參數(as function)

後來看Promise源碼,比較能理解了

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
const PENDING = 'pending';
const FULFILLED = 'fulfilled';
const REJECTED = 'rejected';
function Promise(executor) {
let self = this;
self.status = PENDING;
self.onFulfilled = [];//成功的回调
self.onRejected = []; //失败的回调
//PromiseA+ 2.1
function resolve(value) {
if (self.status === PENDING) {
self.status = FULFILLED;
self.value = value;
self.onFulfilled.forEach(fn => fn());//PromiseA+ 2.2.6.1
}
}

function reject(reason) {
if (self.status === PENDING) {
self.status = REJECTED;
self.reason = reason;
self.onRejected.forEach(fn => fn());//PromiseA+ 2.2.6.2
}
}

try {
executor(resolve, reject);
} catch (e) {
reject(e);
}
}

用簡單的範例來看的話

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function prom(executor) {
let self = this;
function resolve(value) {
console.log(value)
};
function reject(value) {
console.log(value)
};
executor(resolve, reject);
}

let a = new prom((a, b) => {
a('123');
b('abc');
})

// output:
// 123
// abc
CATALOG