前端常用方法——promise的简易实现(包含race, all,wrap以及promise的简易实现)
场景
这几天看基础代码发现有好多自己之前实现的给忘记了,打算重拾记录下,以后有空的时间看下~
Promise的class版本实现
class MyPromise {
constructor(fn) {
this.status = 'pending'
this.successArr = []
this.failArr = []
this.data = ''
fn(this.resolve.bind(this),this.reject.bind(this))
}
resolve(value) {
this.status = 'fullfilled'
this.data = value
this.successArr.map(fn => fn(value))
}
reject(value) {
this.status = 'rejected'
this.data = value
this.failArr.map(fn => fn(value))
}
then(successCallback,failCallback){
if(this.status === 'fullfilled') {
successCallback(this.data)
}else if(this.status === 'rejected') {
failCallback(this.data)
}else if(this.status === 'pending') {
this.successArr.push(successCallback)
this.failArr.push(failCallback)
}
}
catch(failCallback) {
this.then(null,failCallback)
}
}
Promise的all实现
// 使用Promise.resolve方法
Promise.myAll = (arr) => {
const newArr = []
let index = 0
return new Promise(resolve => {
arr.forEach((item,i) => {
Promise.resolve(item).then(data => {
newArr[i] = data
index ++
if(index === arr.length) {
resolve(newArr)
}
})
})
})
}
// 不使用Pomise.resolve方法
Promise.myAll2 = (arr) => {
return new Promise(reslove => {
const newArr = []
let index = 0
const next = (i,data) => {
newArr[i] = data
index ++
if(index === arr.length) {
reslove(newArr)
}
}
arr.forEach((p,i) => {
if(p instanceof Promise) {
p.then(data => next(i,data))
}else {
next(i,p)
}
})
})
}
Promise的race实现
// 使用Promise.resolve
Promise.myRace = (arr) => {
const newArr = []
return new Promise(resolve => {
arr.forEach(item => {
Promise.resolve(item).then(data => {
newArr.push(data)
if(newArr.length === 1) {
resolve(newArr)
return
}
})
})
})
}
// 不使用Promise.resolve
Promise.myRace2 = (arr) => {
return new Promise(resolve => {
const newArr = []
let index = 0
arr.forEach((item,i) => {
if(item instanceof Promise) {
item.then(data => next(i,data))
}else {
next(i,item)
}
})
const next = (i,data) => {
newArr[index ++] = data
if(index === 1) {
resolve(newArr[0])
return
}
}
})
}
Promise的wrap实现
MyPromise.wrap = function(fn) {
return function() {
const args = [].slice.call(arguments)
return new MyPromise(resolve => {
fn.apply(null,args.concat((data) => {
resolve(data)
}))
})
}
}
wrap搭配使用
const request = (url,fn) => {
const xhr = new XMLHttpRequest()
xhr.open('GET',url)
xhr.send(null)
xhr.onreadystatechange = () => {
if(xhr.status === 200 && xhr.readyState === 4) {
const data = xhr.responseText
setTimeout(() => {
fn(data)
},5000)
}
}
}
const pro = MyPromise.wrap(request)
pro('./2021-day-01-05.json').then(data => {
console.log(data)
})
小结
好久没回顾忘了不少,但重拾发现拾起来还是挺快的,平时还是要多看多记,多学多思考!
有啥不对的地方也欢迎指正~