inpm
! dlrow olleH

手写一个符合Promise/A+规范

2019-03-16 js
Word count: 318 | Reading time: 1min

为什么promise出现

  • 解决异步回掉问题
  • 以下情况是如果不要promise
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    // ajax
    function getData(url, data, callback) {
    $.ajax({
    type: 'GET',
    url: url,
    data: data
    success: function(res) {
    $.ajax({
    ...
    $.ajax({
    ...
    })
    })
    }
    })
    }

promise写法, 链式调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function getData(url, data) {
return new Promise((resolve, reject) => {
$.ajax({
type: 'GET',
url: url,
data: data,
success: function(res) {
resolve(res)
},
fail: function(err) {
reject(res)
}
})
})
}

getData(url, data).then(res => {})

promise三种状态

  • pending, 等待
  • fulfilled, 拿result, resolve()
  • rejected, 拿error, reject()

promise规范

  • promise内部一定又一个函数会在传入参数后立即执行
  • 所以我们模拟这个过程,并将三种状态的变化带上
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    function Promise(executor) {
    let _this = this
    _this.status = 'pending'

    function resolve(fn) {
    if(_this.status === 'pending') {
    _this.onResolved.forEach(fn => fn()) // 链式操作需要
    _this.status = 'fulfilled'
    }
    }
    function reject() {
    if(_this.status === 'pending') {
    _this.onResolved.forEach(fn => fn()) // 链式操作需要
    _this.status = 'rejected'
    }
    }

    // 异常处理
    try {
    executor(resolve, reject)
    } catch (err) {
    reject(err)
    }
    }

    // 为Promise添加`.then`方法
    Promise.prototype.then = function(onfulfiled, onrejected) {
    // 入餐处理
    onfulfiled = typeof onfulfiled === 'function' ? onfulfiled : res => res
    onrejected = typeof onrejected === 'function' ? onrejected : err => {throw err}

    let _this = this
    let promise = new Promise((reslove, reject) => {
    switch (_this.status) {
    case 'fulfiled':
    onfulfiled(res)
    break
    case 'rejected':
    onrejected(err)
    break
    default:
    _this.Promise(promise)
    break
    }
    })
    return promise
    }

未完.(待续)

Author: inpm.cy@gmail.com

Link: https://inpm.top/2019/03/16/promise/

Copyright: All articles in this blog are licensed under inpm unless stating additionally.

< PreviousPost
你永运不会准备好,so Just do it!
NextPost >
归家
CATALOG
  1. 1. 为什么promise出现
  2. 2. promise写法, 链式调用
  3. 3. promise三种状态
  4. 4. promise规范
  5. 5. 未完.(待续)