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
global.Promise = (function () {
class Promise {
constructor(callback) {
this.val = undefined;
this.status = "pending";
this.init(callback);
}
onReject = (err) => {
this.val = err;
this.status = "reject";
console.log("onReject is call");
};
onResolve = (val) => {
this.val = val;
this.status = "fulfilled";
console.log("onResolve is call");
};
init(callback) {
callback(this.onResolve, this.onReject);
}
then(resolve, reject) {
if (this.status === "fulfilled") {
resolve(this.val);
} else if (this.status === "reject") {
if (!reject === undefined) reject(this.val);
}
return this;
}
finally(cb) {
if (this.status === "fulfilled" || this.status === "reject") {
cb();
}
}
catch(cb) {
cb(this.val);
return this;
}
}
Promise.reject = function () {};
Promise.resolve = function () {};

return Promise;
})();

function getApi(flag = true) {
return new Promise((resolve, reject) => {
if (flag) {
resolve(123);
} else {
reject(new Error("你错了!"));
}
});
}
getApi(true)
.then((res) => {
console.log(res);
return 123;
})
.then((val) => {
console.log(val);
});