<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="./1.js"></script>
</head>
<body></body>
<script>
let p = new Mpromise((reslove, reject) => {
setTimeout(() => {
reslove("ok");
}, 1000);
});
let res = p.then(
(value) => {
console.log(value);
throw "抛出异常";
},
(reason) => {
console.log(reason);
}
);
console.log(res);
</script>
</html>
function Mpromise(excutor) {
this.promiseState = "pending"
this.promiseResult = null
this.callbacks = []
const _self = this
function reslove(data) {
if (_self.promiseState !== 'pending') return false
_self.promiseState = 'reslove'
_self.promiseResult = data
_self.callbacks.forEach((item) => {
item.onReslove(data)
})
}
function reject(data) {
if (_self.promiseState !== 'pending') return false
_self.promiseState = 'reject'
_self.promiseResult = data
_self.callbacks.forEach((item) => {
item.onReject(data)
})
}
try {
excutor(reslove, reject)
} catch (error) {
reject(error)
}
}
Mpromise.prototype.then = function (onReslove, onReject) {
var _that = this
return new Mpromise((reslove, reject) => {
if (this.promiseState === "reslove") {
try {
let result = onReslove(this.promiseResult)
if (result instanceof Mpromise) {
result.then((v) => {
reslove(v)
}, (r) => {
reject(r)
})
} else {
reslove(result)
}
} catch (error) {
reject(error)
}
} else if (this.promiseState === "reject") {
onReject(this.promiseResult)
} else {
this.callbacks.push({
onReslove() {
try {
let result = onReslove(_that.promiseResult)
if (result instanceof Mpromise) {
result.then((v) => {
reslove(v)
}, (r) => {
reject(r)
})
} else {
reslove(result)
}
} catch (error) {
reject(error)
}
},
onReject() {
try {
let result = onReject(_that.promiseResult)
if (result instanceof Mpromise) {
result.then((v) => {
reslove(v)
}, (r) => {
reject(r)
})
} else {
reject(result)
}
} catch (error) {
reject(error)
}
}
})
}
})
}