值得传递
then方法不调用参数,可以一直把参数往后传递
let p = new Promise((resolve, reject) => {
resolve('sx')
})
p.then()
.then()
.then((value) => {
console.log(value) //sx
}, (reason) => {
console.log(reason)
})
实现这个原理很简单,只需要在then方法的定义中做一层判断,如果没有传递参数,则构造一个参数,返回需要的数值给下一个Promise
onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : v => v
onRejected = typeof onRejected === 'function' ? onRejected : (err) => { throw err }
resolve和reject的实现
相当于调用Promise中的resolve和reject,可以使用then执行其结果
Promise.resolve(1).then(value => console.log(value)) //1
调用该静态方法,可以令其内部创建一个Promise,改变其状态返回即可
static resolve (value) {
return new Promise((resolve, reject) => {
resolve(value)
})
}
static reject (reason) {
return new Promise((resolve, reject) => {
reject(reason)
})
}
catch实现
值得穿透可以把错误信息放到最后处理,catch就是运用这个原理
static catch (errfn) {
return this.then(null, errfn)
}
all方法的实现
- 调用all,用户传进去一个数组,返回一个Promise
- 创建一个Promise,在里面遍历数组的每一项,如果是Promise
- 执行then,成功态将数据存入数组中
- 失败则调用reject
- 如果是普通值则直接加入数组中
static all (promises) {
return new Promise((resolve, reject) => {
let timer = 0;
let result = []
const processSuccess = function (index, data) {
result[index] = data
if (++timer === promises.length) {
resolve(result)
}
}
for (let i = 0; i < promises.length; ++i) {
let p = promises[i]
//判断是否为promise
if (p && typeof p.then === "function") {
p.then(value => {
processSuccess(i, value)
}, reject)
}
else {
processSuccess(i, p)
}
}
})
}