使用
<!DOCTYPE html>
<html>
<head>
<title>Promise 测试</title>
<script type="text/javascript" src="./promise.js"></script>
</head>
<body>
<script type="text/javascript">
new Promise((resolve, reject) => {
setTimeout(function(){
resolve(10);
}, 10000);
// setTimeout(reject, 1000, '未知异常');
// if (false) {
// resolve("test");
// } else {
// reject("未知异常");
// }
}).then((data) => {
console.log("then11: " + data);
}).then((data) => {
console.log("then12: " + data);
}).catch((e) => {
console.log(e);
});
</script>
</body>
</html>
Promise源代码
/**
* promise 状态: pending, resolved, rejected
*/
function Promise(callback) {
if (typeof callback == 'function') {
// 初始化状态, 默认状态pending,首先没有执行成功或失败函数之前状态是pending
(this.status = 'pending'), this.msg;
// 异步时起作用
this.list = [[],[]];
// 用that存当前this的内容
let that = this
// 回调执行
callback(
function() {
// 设置状态
that.status = 'resolved';
// 设置参数
that.msg = arguments[0];
// 遍历执行
for (const { resolve } of that.list[0]) {
resolve(that.msg);
}
},
function() {
// 设置状态
that.status = 'rejected';
// 设置参数
that.msg = arguments[0];
// 遍历执行
for (const { reject } of that.list[1]) {
reject(that.msg);
}
});
} else {
console.log("callback 不是一个方法.");
}
};
/**向 promise 上添加方法*/
Promise.prototype.then = function() {
if (this.status == 'resolved') {
// 执行方法
arguments[0](this.msg);
} else {
// 实例参数有异步语句的会先执行then
this.list[0].push({ resolve:arguments[0] })
}
return this;
};
/**向 promise 上添加方法*/
Promise.prototype.catch = function() {
if (this.status == 'rejected') {
// 执行方法
arguments[0](this.msg);
} else {
// 实例参数有异步语句的会先执行
this.list[1].push({ reject:arguments[0] })
}
};