用Javascript实现Promise以及Promise.all

一。promise.all

1.返回无序数组

 1  const ajax1 = () => new Promise((res, rej) => {
 2       setTimeout(() => res(1), 1000)
 3     })
 4     const ajax2 = () => new Promise((res, rej) => {
 5       setTimeout(() => res(3), 3000)
 6     })
 7     const ajax3 = () => new Promise((res, rej) => {
 8       setTimeout(() => res(2), 2000)
 9     })
10 
11  const fn1 = arg => new Promise((resolve, reject) => {
12       const arr = []
14       arg.forEach((i, index) => {
16         i.then(res => {
17           arr.push( res )
18           if (arr.length == arg.length) {
19             resolve(arr)
20           }
21         })
22       })
23     })
24  fn1([ajax1(), ajax2(), ajax3()]).then(res => {
25       console.log(res)
26 
27     })

2.返回有序

const fn = arg => new Promise((resolve, reject) => {
      const arr = []
      arg.forEach((i, index) => {
        i.then(res => {
          arr.push({
            index,
            val: res
          })
          if (arr.length == arg.length) {
            arr.sort((a,b)=>a.index-b.index).forEach(obj=>arr[obj.index]=obj.val)
            resolve(arr)
          }
        })
      })
    })

 二。Promise

function Promise(executor) {
  this.PromiseState = 'pending'
  this.PromiseResult = null
  const self = this
  this.task = ()=>{}
  function resolve(value) {
    self.PromiseState = 'fulfilled'
    self.PromiseResult = value
    self.task()
  }
  function reject(reason) {
    self.PromiseState = 'rejected'
    self.PromiseResult = reason
    self.task()
  }
  this.then = function (cb) {
    if (self.PromiseState == 'pending') {
      self.task = () => cb(self.PromiseResult)
    }
    if (self.PromiseState == 'fulfilled') {
      cb(self.PromiseResult)
    }
    return this
  }
  this.catch = function (cb) {
    if (self.PromiseState == 'pending') {
      self.task = () => cb(self.PromiseResult)
    }
    if (self.PromiseState == 'rejected') {
      cb(self.PromiseResult)
    }
    return this
  }
  executor(resolve, reject)
}
//算是初步实现,主要是原理,想办法在异步resolve之后调用then的方法,那么要怎么取到then的方法呢,就是执行then的时候把then的callback赋值给一个变量然后异步的resolve执行的调用即可

 

posted @ 2020-12-18 20:54  番番番茄  阅读(185)  评论(0)    收藏  举报