1
2
3
4
5
6
7
8
9
10
11
12
13
class MyPromise {
constructor(fn) {
fn(value => queueMicrotask(() => this.cb?.(value)))
}
then(onFulfilled) {
return new MyPromise(resolve => this.cb = val => {
const thenCb = onFulfilled(val)
thenCb instanceof MyPromise ? thenCb.then(resolve) : resolve(thenCb)
})
}
}


testCase:

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
let promise = MyPromise
const testCase = [
() => {
new promise((resolve) => {
setTimeout(() => {
resolve(1)
}, 1000)
}
).then((res) => {
console.log(res)
return new promise((resolve) => {
setTimeout(() => {
resolve(2)
}, 1000)
})
}
).then(res => {
console.log(res)
})
},
() => {
let p = new promise((resolve) => {
resolve(1)
}).then((res) => {
console.log(res)
return new promise((resolve) => {
setTimeout(() => {
resolve(2)
}, 150)
})
})
setTimeout(() => {
p.then(res => {
console.log(res)
})
}, 100);
}
]

// testCase[0]()
testCase[1]()