class Promise1 {
constructor(exector) {
if (typeof exector !== "function") {
throw new TypeError("Promise resolver " + exector + " is not a function")
}
this.PromiseStatus = "pending";
this.PromiseValue = undefined;
this.resolveFn = Function.prototype;
this.rejectFn = Function.prototype;
let change = (status, value) => {
if (this.PromiseStatus !== "pending") return;
this.PromiseStatus = status;
this.PromiseValue = value;
let delayTimer = setTimeout(() => {
clearTimeout(delayTimer);
delayTimer = null;
if (this.PromiseStatus === "fulfilled") {
this.resolveFn.call(this, value);
} else {
this.rejectFn.call(this, value);
}
}, 0)
}
let resolve = (value) => {
change("fulfilled", value);
}
let reject = (reason) => {
change("rejected", reason);
}
try {
exector(resolve, reject);
} catch (error) {
reject(error.message);
}
}
then(resolveFn, rejectFn) {
if (typeof resolveFn !== "function") {
resolveFn = function (value) {
return Promise.resolve(value);
}
}
if (typeof rejectFn !== "function") {
rejectFn = function (reason) {
return Promise.reject(reason);
}
}
return new Promise((resolve, reject) => {
this.resolveFn = function (value) {
try {
let x = resolveFn(value);
x instanceof Promise ? x.then(resolve, reject) : resolve(x);
} catch (error) {
reject(error.message)
}
}
this.rejectFn = function (reason) {
try {
let x = rejectFn(reason);
x instanceof Promise ? x.then(resolve, reject) : resolve(x);
} catch (error) {
reject(error.message)
}
}
})
}
catch (rejectFn) {
return this.then(null, rejectFn);
}
static resolve(value) {
return new Promise(resolve => {
resolve(value);
})
}
static reject(reason) {
return new Promise((_, reject) => {
reject(reason);
})
}
static all(promiseArr) {
return new Promise((resolve, reject) => {
let index = 0,
values = [];
for (let i = 0; i < promiseArr.length; i++) {
let item = promiseArr[i];
if (!(item instanceof Promise)) {
item = Promise.resolve(item);
}
item.then(value => {
index++;
values[i] = value;
if (index >= promiseArr.length) {
resolve(values);
}
}).catch(reason => {
reject(reason);
})
}
})
}
}
new Promise1((res,rej)=>{
console.log("pro");
setTimeout(()=>{res('1')},2000);
}).then(d=>console.log(d))
console