IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> JavaScript知识库 -> javascript中Promise封装(进阶) -> 正文阅读

[JavaScript知识库]javascript中Promise封装(进阶)

👨🏼?🦳👨🏼?🦰 文件结构 以及 方法了解 🧓🏼

👇 index.html

👇 promise.js

接下来我们将封装 promise实例方法 👇

then
catch


接下来我们将封装 promise静态方法 👇

resolve
reject
all
race

01 - 搭建基本结构 🍠

index.html

let p = new Promise((resolve,reject) => {
	
})

promise.js

class Promise {
	constructor(executor) {
		
	}
}

02 - Promise中 resolve 和 reject 结构 🥩

index.html

let p = new Promise((resolve,reject) => {
	resolve();
	reject();
	throw "errro";
})

promise.js
Promise 中有 三种 状态:
pending 未决定的
fulfilled 成功的
rejected 失败的
调用里面的 resolve 则状态改变为 fulfilled
调用里面的 reject 则状态改变为 rejected
如果什么都不写则状态默认为 pending
如果在抛出错误则 返回一个 rejected 状态。
注意:
promise 中只能改变一次状态,则下面的代码会进行忽略。

class Promise {
	constructor(executor) {
	    this.PromiseState = "pending";
	    this.PromiseResult = null;
	    var resolve = value => {
	      if (this.PromiseState != "pending") return;
	      this.PromiseState = "fulfilled";
	      this.PromiseResult = value;
	    }
	    var reject = reason => {
	      if (this.PromiseState != "pending") return;
	      this.PromiseState = "rejected";
	      this.PromiseResult = reason;
	    }
	    try {
	      executor(resolve,reject);
	    } catch (e) {
	      reject(e);
	    }
	}
}

03 - Promise中 then 方法 🌯

index.html

let p = new Promise((resolve, reject) => {
  setTimeout(() => {
    // resolve('123');
    reject("error");
  }, 1000);
  // reject("error");
  // throw "error";
});
// console.log(p);
let res = p.then(
  value => {
    console.log(value);
    // return "123";
    return new Promise((resolve, reject) => {
      // resolve("123");
      reject("error");
      // throw "error";
    });
  },
  reason => {
    console.log(reason);
    // return "123";
    return new Promise((resolve, reject) => {
      // resolve("123");
      // reject("error");
      // throw "error";
    });
  }
);
console.log(res);

promise.js

class Promise {
	constructor(executor) {
    this.callBack = [];
    this.PromiseState = "pending";
    this.PromiseResult = null;
    var resolve = value => {
      if (this.PromiseState != "pending") return;
      this.PromiseState = "fulfilled";
      this.PromiseResult = value;
      this.callBack.forEach(item => {
        item.onResolved(value);
      })
    }
    var reject = reason => {
      if (this.PromiseState != "pending") return;
      this.PromiseState = "rejected";
      this.PromiseResult = reason;
      this.callBack.forEach(item => {
        item.onRejected(reason);
      })
    }
    try {
      executor(resolve,reject);
    } catch (e) {
      reject(e);
    }
    
	}

  then(onResolved,onRejected) {
    return new Promise((resolve,reject) => {
      let callBack = (type) => {
        try {
          // 获取回调函数执行结果
          let result = type(this.PromiseResult);
          // console.log(result);
          if (result instanceof Promise) {
            result.then(v => {
              resolve(v);
            }, r => {
              reject(r);
            })
          } else {
            resolve(result);
          }
        } catch (e) {
          reject(e);
        }
      }
      // 成功的
      if (this.PromiseState == "fulfilled") {
        callBack(onResolved)
      }
      // 失败的
      if (this.PromiseState == "rejected") {
        callBack(onRejected);
      }
      // 未决定的
      if (this.PromiseState == "pending") {
        this.callBack.push({
          onResolved: () => {
            callBack(onResolved);
          },
          onRejected: () => {
            callBack(onRejected);
          },
        })
      };
    })
  }
}

04 - Promise中 catch 方法 🥠

index.html

let p = new Promise((resolve, reject) => {
  reject("error");

  // throw "213";
  // resolve("213");
});

let res = p
  .then(value => {
    console.log(111);
  })
  .then(value => {
    console.log(222);
  })
  .catch(reason => {
    console.log(reason);
  });
console.log(res);

promise.js

class Promise {
	constructor(executor) {
    this.callBack = [];
    this.PromiseState = "pending";
    this.PromiseResult = null;
    var resolve = value => {
      if (this.PromiseState != "pending") return;
      this.PromiseState = "fulfilled";
      this.PromiseResult = value;
      this.callBack.forEach(item => {
        item.onResolved(value);
      })
    }
    var reject = reason => {
      if (this.PromiseState != "pending") return;
      this.PromiseState = "rejected";
      this.PromiseResult = reason;
      this.callBack.forEach(item => {
        item.onRejected(reason);
      })
    }
    try {
      executor(resolve,reject);
    } catch (e) {
      reject(e);
    }
    
	}

  then(onResolved,onRejected) {
    if (typeof onResolved != "function") {
      onResolved = value => value;
    }
    if (typeof onRejected !== "function") {
      onRejected = reason => {
        throw reason;
      }
    }
    return new Promise((resolve,reject) => {

      let callBack = (type) => {
        try {
          // 获取回调函数执行结果
          let result = type(this.PromiseResult);
          // console.log(result);
          if (result instanceof Promise) {
            result.then(v => {
              resolve(v);
            }, r => {
              reject(r);
            })
          } else {
            resolve(result);
          }
        } catch (e) {
          reject(e);
        }
      }
      // 成功的
      if (this.PromiseState == "fulfilled") {
        callBack(onResolved)
      }
      // 失败的
      if (this.PromiseState == "rejected") {
        callBack(onRejected);
      }
      // 未决定的
      if (this.PromiseState == "pending") {
        this.callBack.push({
          onResolved: () => {
            callBack(onResolved);
          },
          onRejected: () => {
            callBack(onRejected);
          },
        })
      };
    })
  }

  catch(fn) {
    return this.then(undefined,fn);
  }
}

05 - Promise 中 resolve 方法 🥙

index.html

let p = Promise.resolve(
  new Promise((resolve, reject) => {
    // resolve("123");
    // reject("error");
    throw "wee";
  })
);
console.log(p);

promise.js

static resolve(data) {
  return new Promise((resolve,reject) => {
    try {
      if (data instanceof Promise) {
        data.then(value => {
          resolve(value);
        },reason => {
          reject(reason);
        })
      } else {
        resolve(data);
      }
    }catch(e) {
      reject(e);
    }
  }) 
}

05 - Promise 中 reject 方法 🥪🥟🌮

index.html

let p = Promise.reject(
  // "error"
  // new Promise((resolve, reject) => {
  //   // resolve("123");
  //   // reject("error");
  //   throw "wee";
  // })
);
console.log(p);

promise.js

static reject(data) {
 return new Promise((resolve,reject) => {
   reject(data);
 })
}

06 - Promise 中 all 方法 🥟🌮

index.html

let p1 = new Promise((resolve, reject) => {
  resolve("OK");
});

let p2 = Promise.resolve("nice");
let p3 = Promise.resolve("nice a");
let res = Promise.all([p1, p2, p3]);
console.log(res);

promise.js

static all(value) { 
  return new Promise((resolve,reject) => {
    let count = 0;
    let arr = [];
    value.forEach((item,index) => {
      item.then(v => {
        count++;
        arr[index] = v;
        if (count === value.length) {
          resolve(arr);
        }
      },r => {
        reject(r);
      })
    })
  })
}

07 - Promise 中 race 方法 🥟

index.html

let p1 = new Promise((resolve, reject) => {
  resolve("OK");
});

let p2 = Promise.resolve("nice");
let p3 = Promise.resolve("nice a");
let res = Promise.all([p1, p2, p3]);
console.log(res);

promise.js

static all(value) { 
  return new Promise((resolve,reject) => {
    let count = 0;
    let arr = [];
    value.forEach((item,index) => {
      item.then(v => {
        count++;
        arr[index] = v;
        if (count === value.length) {
          resolve(arr);
        }
      },r => {
        reject(r);
      })
    })
  })
}

完整代码 🌮

class Promise {
	constructor(executor) {
    this.callBack = [];
    this.PromiseState = "pending";
    this.PromiseResult = null;
    var resolve = value => {
      if (this.PromiseState != "pending") return;
      this.PromiseState = "fulfilled";
      this.PromiseResult = value;
      this.callBack.forEach(item => {
        item.onResolved(value);
      })
    }
    var reject = reason => {
      if (this.PromiseState != "pending") return;
      this.PromiseState = "rejected";
      this.PromiseResult = reason;
      this.callBack.forEach(item => {
        item.onRejected(reason);
      })
    }
    try {
      executor(resolve,reject);
    } catch (e) {
      reject(e);
    }
    
	}

  then(onResolved,onRejected) {
    if (typeof onResolved != "function") {
      onResolved = value => value;
    }
    if (typeof onRejected !== "function") {
      onRejected = reason => {
        throw reason;
      }
    }
    return new Promise((resolve,reject) => {

      let callBack = (type) => {
        try {
          // 获取回调函数执行结果
          let result = type(this.PromiseResult);
          // console.log(result);
          if (result instanceof Promise) {
            result.then(v => {
              resolve(v);
            }, r => {
              reject(r);
            })
          } else {
            resolve(result);
          }
        } catch (e) {
          reject(e);
        }
      }
      // 成功的
      if (this.PromiseState == "fulfilled") {
        callBack(onResolved)
      }
      // 失败的
      if (this.PromiseState == "rejected") {
        callBack(onRejected);
      }
      // 未决定的
      if (this.PromiseState == "pending") {
        this.callBack.push({
          onResolved: () => {
            callBack(onResolved);
          },
          onRejected: () => {
            callBack(onRejected);
          },
        })
      };
    })
  }

  catch(fn) {
    return this.then(undefined,fn);
  }

  static resolve(data) {
    return new Promise((resolve,reject) => {
      try {
        if (data instanceof Promise) {
          data.then(value => {
            resolve(value);
          },reason => {
            reject(reason);
          })
        } else {
          resolve(data);
        }
      }catch(e) {
        reject(e);
      }
    }) 
  }

  static reject(data) {
    return new Promise((resolve,reject) => {
      reject(data);
    })
  }

  static all(value) {
    
    return new Promise((resolve,reject) => {
      let count = 0;
      let arr = [];
      value.forEach((item,index) => {
        item.then(v => {
          count++;
          arr[index] = v;
          if (count === value.length) {
            resolve(arr);
          }
        },r => {
          reject(r);
        })
      })
    })
  }

  static race(value) {
    return new Promise((resolve,reject) => {
      value.forEach(item => {
        item.then(v => {
          resolve(v);
        },r => {
          reject(r);
        })
      })
    })
  }

}
  JavaScript知识库 最新文章
ES6的相关知识点
react 函数式组件 & react其他一些总结
Vue基础超详细
前端JS也可以连点成线(Vue中运用 AntVG6)
Vue事件处理的基本使用
Vue后台项目的记录 (一)
前后端分离vue跨域,devServer配置proxy代理
TypeScript
初识vuex
vue项目安装包指令收集
上一篇文章      下一篇文章      查看所有文章
加:2021-08-22 13:28:04  更:2021-08-22 13:29:24 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/23 13:01:17-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码