Promise.then 函数接受两个函数,第一个函数执行成功回调(onResolve),第二个函数执行错误回调(onRejected),并且返回的是一个Promise对象
分析
1.then 对接的是“.”前的promise对象 p1
2.onResolve是在p1为‘resolve’时候执行,onRejected是在p1为‘rejected’时候执行,故和p1的状态有关系,所以有可能是一个异步或者是一个同步执行(同步执行代表p1的状态已经改变了,不为‘pending’,比如:new时候执行resolve)
3.onResolve/onRejected 或者返回的是一个新的promise时候,这次的执行结果一定和新的promise相关。
代码
function Promise(fun) { // promise的状态 this.promiseState = "pending"; // promise的结果 this.promiseResult = null; // 存放异步回调 this.callbackList = []; const resolve = (val) => { if (this.promiseState !== "pending") return; this.promiseState = "fulfilled"; this.promiseResult = val; console.log("this.callbackList: ", this.callbackList); for (let index = 0; index < this.callbackList.length; index++) { const element = this.callbackList[index]; element.onResolve(val); } }; const reject = (err) => { if (this.promiseState !== "pending") return; this.promiseState = "rejected"; this.promiseResult = err; for (let index = 0; index < this.callbackList.length; index++) { const element = this.callbackList[index]; element.onRejected(err); } }; try { fun(resolve, reject); } catch (error) { reject(error); }}Promise.prototype.then = function (onResolve, onRejected) { const self = this; //返回一个promise return new Promise((resolve, reject) => { const handleCallback = (callback) => { try { //onResolve 或者onRejected执行时候可能返回一个promise对象 const res = callback(self.promiseResult); //返回的是promise if (res instanceof Promise) { res.then( (val) => { resolve(val); }, (err) => { reject(err); } ); } else { // 返回的不是 resolve(res); } } catch (error) { reject(error); } }; if (self.promiseState === "pending") { // 异步时候放在回调里面执行 self.callbackList.push({ onResolve: () => { handleCallback(onResolve); }, onRejected: () => { handleCallback(onRejected); }, }); } //同步时候之执行 if (self.promiseState === "fulfilled") { console.log("self.promiseState: ", self.promiseState); handleCallback(onResolve); } if (self.promiseState === "rejected") { handleCallback(onRejected); } });};
测试代码
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> </head> <script src="./Promise.js"></script> <body> <h3>Promise构造函数</h3> <div> Promise接受一个函数,该函数接受两个参数,两个参数可以改变promise的状态promiseState,状态一旦改变,不允许再次改动了 </div> <script> const p1 = new Promise((resolve, reject) => { setTimeout(() => { resolve(123); }, 3000); }); p1.then( (val) => { console.log("val: ", val); return new Promise((resolve, reject) => { setTimeout(() => { resolve(123 + val); }, 3000); }); }, (err) => { console.log("err: ", err); } ).then( (val) => { console.log("val1: ", val); }, (err) => { console.log("err: ", err); } ); </script> </body></html>
网友评论