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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
function MyPromise(fn) {
let state = "pending";
let value = null;
const callbacks = [];

this.then = function (onFulfilled) {
return new MyPromise((resolve, reject) => {
handle({
//桥梁,将新 Promise 的 resolve 方法,放到前一个 promise 的回调对象中
onFulfilled,
resolve,
});
});
};

function handle(callback) {
if (state === "pending") {
callbacks.push(callback);
return;
}

if (state === "fulfilled") {
if (!callback.onFulfilled) {
callback.resolve(value);
return;
}
const ret = callback.onFulfilled(value); //处理回调
callback.resolve(ret); //处理下一个 promise 的resolve
}
}
function resolve(newValue) {
const fn = () => {
if (state !== "pending") return;

state = "fulfilled";
value = newValue;
handelCb();
};

queueMicrotask(fn); //基于 PromiseA+ 规范
}

function handelCb() {
while (callbacks.length) {
const fulfiledFn = callbacks.shift();
handle(fulfiledFn);
}
}
fn(resolve);
}
new MyPromise((resolve, reject) => {
debugger;
setTimeout(() => {
resolve(20);
}, 0);
}).then((data) => {
console.log(data);
});
console.log(1);
setTimeout(() => {
console.log(2);
}, 0);