7、then方法执行回调
- then方法里的两个形参实际对应着两个参数(函数),并且自己也带参(存储在PromiseResult里),因此要实现onResolved和onRejected两个函数的逻辑
- 这里要判断PromiseState的状态,因为在resolve或reject的时候,已经实现修改了PromiseState的值(resolvue和reject隐含的第一项操作就是修改PromiseState的值,第二不就是修改PromiseResult的值)
function Promise(excutor){
this.PromiseState='pending'
this.PromiseResult=''
const that=this
function resolve (data) {
if (that.PromiseState!=='pending'){
return
}
that.PromiseState='fulfilled'
that.PromiseResult=data
}
function reject (data) {
if (that.PromiseState!=='pending'){
return
}
that.PromiseState='rejected'
that.PromiseResult=data
}
try{
excutor(resolve,reject)
}
catch (e) {
reject(e)
}
}
Promise.prototype.then=function(onResolved,onRejected){
if (this.PromiseState=='fulfilled'){
onResolved(this.PromiseResult)
}
if (this.PromiseState=='rejected'){
onRejected(this.PromiseResult)
}
}
8、异步的执行逻辑
- 要处理处理异步调用,异步的时候,then先被执行,因此,此刻的PromiseState的状态是‘pending’,因此要在then方法中有响应的对‘pending’状态的处理逻辑
- 由于异步状态下,then方法先执行,然后PromiseState才被改变,因此,当遇到PromiseState的值为‘pending’的时候,应当先保存onResolved和onRejected带到PromiseState发生改变的时候再去执行
- 由于the的作用域和执行器函数的作用域不一致,因此要在Promise的类属性中保存一个callback属性(用json格式)。
- 最后在生成器函数中去执行这个callback属性包含的onResolved和onRejected方法
function Promise(excutor){
this.PromiseState='pending'
this.PromiseResult=''
this.callback={
}
const that=this
function resolve (data) {
if (that.PromiseState!=='pending'){
return
}
that.PromiseState='fulfilled'
that.PromiseResult=data
if (that.callback.onResolved){
that.callback.onResolved(data)
}
}
function reject (data) {
if (that.PromiseState!=='pending'){
return
}
that.PromiseState='rejected'
that.PromiseResult=data
if (that.callback.onRejected){
that.callback.onRejected(data)
}
}
try{
excutor(resolve,reject)
}
catch (e) {
reject(e)
}
}
Promise.prototype.then=function(onResolved,onRejected){
if (this.PromiseState=='fulfilled'){
onResolved(this.PromiseResult)
}
if (this.PromiseState=='rejected'){
onRejected(this.PromiseResult)
}
if (this.PromiseState=='pending'){
this.callback={
onResolved,
onRejected
}
}
}

9、指定多个回调
- 如果有多个回调的情形,then的多个成功的resolve都可以执行
- 但多个then每次都会将callback属性保存并覆盖之前的信息,导致只能执行最后一个onResolved或onRejected,因此要将callback作为一个数组来保存
- 每次then执行的时候将then所在的onResolved或onRejected方法push到数组中去
- 使用时,按顺序遍历数组中的事件回调函数,这样就做到了依次执行
function Promise(excutor){
this.PromiseState='pending'
this.PromiseResult=''
this.callbacks=[]
const that=this
function resolve (data