点我看看~ 话不多说,上源码:
// 核心方法!核心方法!核心方法!也是最难懂的!—-START
const resolvePromise = (promise2, x, resolve, reject) => {
if (promise2 === x) {
return reject(new TypeError(“A promise cannot be resolved with itself”))
}
if (x && (typeof x === “object” || typeof x === “function”)) {
try {
let then = x.then;
if (typeof then === “function”) {
then.call(x, y => {
resolve(y);
resolvePromise(promise2, y, resolve, reject);
}, r => {
reject(r);
})
} else {
resolve(x);
}
} catch (e) {
reject(e)
}
} else {
resolve(x)
}
};
// 核心方法!核心方法!核心方法!也是最难懂的!—-END
// Commitment 就是
class Commitment {
constructor (executor) {
this.status = “PENDING”
this.value = void(0);
this.reason = void(0);
this.onResolvedCallbacks = [];
this.onRejectedCallbacks = [];
const resolve = (value) => {
if (this.status === “PENDING”) {
this.status = “RESOLVED”;
this.value = value;
this.onResolvedCallbacks.forEach(cb => cb())
}
}
const reject = (reason) => {
if (this.status === “PENDING”) {
this.status = “REJECTED”;
this.reason = reason;
this.onRejectedCallbacks.forEach(cb => cb())
}
}
try {
executor(resolve, reject)
} catch (e) {
reject(e)
}
}
then (onResolvedFn, onRejectedFn) {
let promise2, x;
promise2 = new Promise((resolve, reject) => {
if (this.status === “RESOLVED”) {
setTimeout(() => {
try {
x = onResolvedFn(this.value);
resolvePromise(promise2, x, resolve, reject);
} catch(e) {
reject(e)
}
}, 0)
}
if (this.status === “REJECTED”) {
setTimeout(() => {
try {
x = onRejectedFn(this.reason);
resolvePromise(promise2, x, resolve, reject)
} catch (e) {
reject(e)
}
}, 0)
}
if (this.status === “PENDING”) {
this.onResolvedCallbacks.push(() => {
setTimeout(() => {
try {
x = onResolvedFn(this.value);
resolvePromise(promise2, x, resolve, reject)
} catch (e) {
reject(e)
}
}, 0)
});
this.onRejectedCallbacks.push(() => {
setTimeout(() => {
try {
x = onRejectedFn(this.reason);
resolvePromise(promise2, x, resolve, reject)
} catch (e) {
reject(e)
}
}, 0)
});
}
});
return promise2
}
catch (onRejectedFn) {
return this.then(null, onRejectedFn)
}
// 静态方法
static resolve (value) {
return new Commitment((resolve, reject) => {
resolve(value)
})
}
static reject (err) {
return new Commitment((resolve, reject) => {
reject(err)
})
}
static all () {
let result = [];
return new Commitment((resolve, reject) => {
if (arguments.length === 0) {
return reject(new TypeError(“undefined is not iterable (cannot read property Symbol(Symbol.iterator))”))
} else {
let args = […arguments][0], result = [];
let count = args.length, num = 0;
for (let i = 0; i < count; i++) {
let item = args[i];
try {
let then = item.then;
if (typeof then === “function”) {
then.call(item, y => {
num += 1;
result[i] = y;
if (num === count) {
resolve(result)
}
}, r => {
reject(r)
})
} else {
result[i] = item;
if (num === count) {
resolve(result)
}
}
} catch (e) {
reject(e)
}
}
}
})
}
static race () {
// 未完待续
}
}