第一章:手写 Promise
// 手写 Promise
// status = 'pending' 挂起状态
// status = 'fulfilled' 成功状态
// status = 'fulfilled' 失败状态
// result = data 保存返回值
function MyPromise(){
this.status = 'pending' //挂起状态
console.log(this)
let { resolve, reject } = this.constructor
if(typeof arguments[0] != 'function'){
console.error('Promise: 构造函数第一个参数必须是函数')
return
}
arguments[0](resolve.bind(this), reject.bind(this))
}
MyPromise.resolve = function(data){
// 保存值 和 更改状态
this.result = data
this.status = 'fulfilled' //成功状态
}
MyPromise.reject = function(data){
// 保存值 和 更改状态
this.result = data
this.status = 'fulfilled' //失败状态
}
MyPromise.prototype.then = function(){
let val = null
if(this.status == 'fulfilled' && typeof arguments[0] == 'function'){
val = arguments[0](this.result)
}
if(val != null){
//有返回值则保留 status = 'fulfilled' 成功状态
//保存返回值
this.result = val
} else {
//无返回值则 更改 status = 'pending' 挂起状态
this.status = 'pending' //挂起状态
}
return this
}
MyPromise.prototype.catch = function(){
if(this.status == 'rejected' && typeof arguments[0] == 'function'){
arguments[0](this.result)
}
// 失败状态不管有没有返回值,直接更改为挂起状态
this.status = 'pending' //挂起状态
return this
}
// 构建 promise 对象
new MyPromise(function(resolve, reject){
resolve(1)
}).then(function(data){
console.log('then1',data)
// 有返回值,会继续调用下一个 then
return data + 1
}).then(function(data){
//没返回值不会继续调用 then
console.log('then2',data)
}).catch(function(data){
console.log('catch',data)
// 调用 catch 之后,后面都不会继续调用 then 或 catch
return 3
}).then(function(data){
//不会在调用....
console.log('then3',data)
})