4.简单代码实现Promise有7个主要的属性state(状态),value(成功放回值),reason(错误信息),resolve方法,reject方法,then方法。
- //1.实际Promise
- //new Promise((resolve,reject)=>{ resolve("zhangpanpan")}))
- //实现简易版Promise
- class MyPromise {
- constructor(exccutor) {
- this.state = "pending"; //当前执行的状态
- this.value; //正确或错误情况下的放回值
- //resolvue 保存正确情况下的返回值
- let resolvue = value => {
- if (this.state === "pending") {
- this.state = "fulfilled";
- this.value = value;
- }
- }
- //reject 情况执行 的函数
- let reject = value => {
- if (this.state === "pending") {
- this.state = "rejected";
- this.value = value;
- }
- }
- try {
- exccutor(resolvue, reject)
- } catch (error) {
- reject(error)
- }
- }
- then(onfulfilled, onJected) {
- if (this.state === "rejected") {
- onJected(this.value)
- }
- if(this.state === "fulfilled"){
- onfulfilled(this.value)
- }
- }
- }
- let mypromise=new MyPromise((res,rej)=>{
- res("ddd")
- });
- mypromise.then(e=>{
- console.log(e);
- })
-