const PENDING = "pending"
const FULFILLED = "fulfilled"
const REJECTED = "rejected"
function MyPromise(callback) {
var _this = this
_this.currentState = PENDING
_this.value = void 0
_this.onResolvedCallbacks = []
_this.onRejectedCallbacks = []
_this.resolve = function (value) {
if (value instanceof MyPromise) {
return value.then(_this.resolve, _this.reject)
}
queueMicrotask(() => {
if (_this.currentState === PENDING) {
_this.currentState = FULFILLED
_this.value = value
_this.onResolvedCallbacks.forEach(cb => cb())
}
})
}
_this.reject = function (value) {
queueMicrotask(() => {
if (_this.currentState === PENDING) {
_this.currentState = REJECTED
_this.value = value
_this.onRejectedCallbacks.forEach(cb => cb())
}
})
}
callback(_this.resolve, _this.reject)
}
MyPromise.resolve=function (value) {
return new MyPromise(resolve => {
resolve(value);
}).then();
}
MyPromise.prototype.then = function(onFulfilled, onRejected) {
var _this = this
var promise2
onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : value => value
onRejected = typeof onRejected === 'function' ? onRejected : error => {throw error}
if (_this.currentState === FULFILLED) {
return promise2 = new MyPromise(function(resolve, reject) {
queueMicrotask(function() {
try {
var x = onFulfilled(_this.value)
if (x instanceof MyPromise) {
x.then(resolve, reject)
}
resolve(x)
} catch (err) {
reject(err)
}
})
})
}
if (_this.currentState === REJECTED) {
return promise2 = new MyPromise(function(resolve, reject) {
queueMicrotask(function() {
try {
var x = onRejected(_this.value)
if (x instanceof Promise){
x.then(resolve, reject)
}
} catch(err) {
reject(err)
}
})
})
}
if (_this.currentState === PENDING) {
return promise2 = new MyPromise(function(resolve, reject) {
_this.onResolvedCallbacks.push(function() {
try {
var x = onFulfilled(_this.value)
if (x instanceof MyPromise) {
x.then(resolve, reject)
}
resolve(x)
} catch(err) {
reject(err)
}
})
_this.onRejectedCallbacks.push(function() {
try {
var x = onRejected(_this.value)
if (x instanceof MyPromise) {
x.then(resolve, reject)
}
} catch (err) {
reject(err)
}
})
})
}
}
MyPromise.resolve().then(() => {
console.log(1);
}).then(() => {
console.log(2);
}).then(() => {
console.log(3);
}).then(() => {
console.log(5);
}).then(() =>{
console.log(6);
})
MyPromise.resolve().then(() => {
console.log(0);
return MyPromise.resolve(4);
}).then((res) => {
console.log(res)
})