首先声明定义类并声明Promise状态与值,有以下几个细节需要注意。
- executor为执行者
- 当执行者出现异常时触发拒绝状态
- 使用静态属性保存状态值
- 状态只能改变一次,所以在resolve与reject添加条件判断
- 因为
resolve
或rejected
方法在executor中调用,作用域也是executor作用域,这会造成this指向window,现在我们使用的是class定义,this为undefined。
class HD { static PENDING = "pending"; static FULFILLED = "fulfilled"; static REJECTED = "rejected"; constructor(executor) { this.status = HD.PENDING; this.value = null; try { executor(this.resolve.bind(this), this.reject.bind(this)); } catch (error) { this.reject(error); } } resolve(value) { if (this.status == HD.PENDING) { this.status = HD.FULFILLED; this.value = value; } } reject(value) { if (this.status == HD.PENDING) { this.status = HD.REJECTED; this.value = value; } } }
下面测试一下状态改变
<script src="HD.js"></script> <script> let p = new HD((resolve, reject) => { resolve("123"); }); console.log(p); </script>