function myPromise(constructor){
let self=this;// 1.为什么要用self来获取this?直接用this不可以吗?
self.status="pending"
self.value=undefined;//2.value和reason不可以用同一个变量吗?
self.reason=undefined;
function resolve(value){
if(self.status==="pending"){
self.value=value;
self.status="resolved";
}
}
function reject(reason){
if(self.status==="pending"){
self.reason=reason;
self.status="rejected";
}
}
try{
constructor(resolve,reject);
}catch(e){
reject(e);
}
}
myPromise.prototype.then=function(onFullfilled,onRejected){//3.then方法为什么要写在原型上?
let self=this;//4.此处的this和构造函数中的this为什么指向是一样的?
switch(self.status){
case "resolved":
onFullfilled(self.value);
break;
case "rejected":
onRejected(self.reason);
break;
default:
}
}
@TOC
先导:promise的使用
1. 三个要点
其中onFulfilled方法表示状态从pending——>fulfilled(resolved)时所执行的方法,而onRejected表示状态从pending——>rejected所执行的方法。
2. 实现步骤
1. v1.0 初始版本myPromise
大致思路如下(已实现上述1、2两点):
myPromise.prototype.then=function(onFullfilled,onRejected){//3.then方法为什么要写在原型上? let self=this;//4.此处的this和构造函数中的this为什么指向是一样的? switch(self.status){ case "resolved": onFullfilled(self.value); break; case "rejected": onRejected(self.reason); break; default:
} }
疑问点: 1、为什么要在resolve和reject中执行回调,而不是在then函数中执行? 我理解的执行回调的一个基本时间点是:status在哪个地方由pending变为resolved和rejected
执行的顺序:
所以如果还是按照1.0版本的myPromise,会导致then中的回调函数不执行,因为在执行then函数时的status是pending,不匹配任何case。
2、按照2.0的方式,相当于在两个地方都执行了then中的回调函数,这样会不会导致回调函数执行两遍? 不会,因为在then中,只有case为pending时,才把回调函数push到数组里,其他情况,数组为空。
3. v3.0then方法实现链式调用
具体思路:then方法实现链式调用的前提时,then方法的返回值也是一个promise。(将2.0中的then方法的每一个case都用myPromise封装)