草庐IT

手写Promise方法(实现Promise A+规范)

chscript 2023-03-28 原文

手写Promise


Promise 构造函数

我们先来写 Promise 的构造函数。需要处理的事件如下:

  1. Promise 状态记录:this.state
  2. 记录成功或失败的值:this.valuethis.reason
  3. 收集解决和拒绝回调函数:this.resolveCallbacksthis.rejectCallbacks
  4. 执行首次传入的解决和拒绝回调函数:func(this.resolve, this.reject)
class myPromise {
    constructor(func) {
        this.state = 'pending' // Promise状态
        this.value = undefined // 成功的值
        this.reason = undefined // 失败的值
        this.resolveCallbacks = [] // 收集解决回调函数
        this.rejectCallbacks = [] // 收集拒绝回调函数
        try { // 对传入的函数进行try...catch...做容错处理
            func(this.resolve, this.reject) // 执行首次传入的两个回调函数
        } catch (e) {
            this.reject(e)
        }
    }
}

三个状态(pending、rejected和fulfilled)

pending:待定状态。待定Promise。只有在then方法执行后才会保持此状态。

fulfilled:解决状态。终止Promise。只有在resolve方法执行后才会由pending更改为此状态。

rejected:拒绝状态。终止Promise。只有在reject方法执行后才会由pending更改为此状态。

注意:其中只有pedding状态可以变更为rejectedfulfilledrejectedfulfilled不能更改其他任何状态。


三个方法(resolve、reject和then)

resolve方法实现要点

  1. 状态由pendingfulfilled。
  2. resolve方法传入的value参数赋值给this.value
  3. 按顺序执行resolveCallbacks里面所有解决回调函数
  4. 利用call方法将解决回调函数内部的this绑定为undefined

坑点 1resolve方法内部this指向会丢失,进而造成this.value丢失。

解决办法:我们将resolve方法定义为箭头函数。在构造函数执行后,箭头函数可以绑定实例对象的this指向。

// 2.1. Promise 状态
resolve = (value) => { // 在执行构造函数时内部的this通过箭头函数绑定实例对象
    if (this.state === 'pending') {
        this.state = 'fulfilled' // 第一点
        this.value = value // 第二点
        while (this.resolveCallbacks.length > 0) { // 第三点
            this.resolveCallbacks.shift().call(undefined) // 第四点
        }
    }
}

reject方法实现要点

  1. 状态由pendingrejected
  2. reject方法传入的reason参数赋值给this.reason
  3. 按顺序执行rejectCallbacks里面所有拒绝回调函数
  4. 利用call方法将拒绝回调函数内部的this绑定为undefined

坑点 1reject 方法内部this指向会丢失,进而造成this.reason丢失。

解决办法:我们将reject方法定义为箭头函数。在构造函数执行后,箭头函数可以绑定实例对象的this指向。

// 2.1. Promise 状态
reject = (reason) => { // 在执行构造函数时内部的this通过箭头函数绑定实例对象
    if (this.state === 'pending') {
        this.state = 'rejected' // 第一点
        this.reason = reason // 第二点
        while (this.rejectCallbacks.length > 0) {  // 第三点
            this.rejectCallbacks.shift().call(undefined) // 第四点
        }
    }
}

then方法实现要点

  1. 判断then方法的两个参数onRejectedonFulfilled是否为function

    1.1 onRejectedonFulfilled都是function,继续执行下一步。

    1.2 onRejected不是function,将onRejected赋值为箭头函数,参数为reason执行throw reason

    1.3 onFulfilled不是function,将onFulfilled赋值为箭头函数,参数为value执行return value

  2. 当前Promise状态为rejected

    2.1 onRejected方法传入this.reason参数,异步执行。

    2.2 对执行的onRejected方法做容错处理,catch错误作为reject方法参数执行。

  3. 当前Promise状态为fulfilled

    3.1 onFulfilled方法传入this.value参数,异步执行。

    3.2 对执行的onFulfilled方法做容错处理,catch错误作为reject方法参数执行。

  4. 当前Promise状态为pending

    4.1 收集onFulfilledonRejected两个回调函数分别pushresolveCallbacksrejectCallbacks

    4.2 收集的回调函数同样如上所述,先做异步执行再做容错处理

  5. 返回一个 Promise 实例对象。

// 2.2. then 方法
then(onFulfilled, onRejected) {
    onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : value => value // 第一点 
    onRejected = typeof onRejected === 'function' ? onRejected : reason => { throw reason } // 第一点 
    const p2 = new myPromise((resolve, reject) => {
        if (this.state === 'rejected') { // 第二点
            queueMicrotask(() => {
                try {
                    onRejected(this.reason)
                } catch (e) {
                    reject(e)
                }
            })
        } else if (this.state === 'fulfilled') { // 第三点
            queueMicrotask(() => {
                try {
                    onFulfilled(this.value)
                } catch (e) {
                    reject(e)
                }
            })
        } else if (this.state === 'pending') { // 第四点
            this.resolveCallbacks.push(() => {
                queueMicrotask(() => {
                    try {
                        onFulfilled(this.value)
                    } catch (e) {
                        reject(e)
                    }
                })
            })
            this.rejectCallbacks.push(() => {
                queueMicrotask(() => {
                    try {
                        onRejected(this.reason)
                    } catch (e) {
                        reject(e)
                    }
                })
            })
        }
    })
    return p2 // 第五点
}

Promise 解决程序(resolvePromise方法)

旁白:其实这个解决程序才是实现核心Promise最难的一部分。因为Promise A+规范对于这部分说的比较绕。

我们直击其实现要点,能跑通所有官方用例就行。如下:

  1. 如果x和promise引用同一个对象:

    1.1 调用reject方法,其参数为new TypeError()

  2. 如果x是一个promise或x是一个对象或函数:

    2.1 定义一个called变量用于记录then.call参数中两个回调函数的调用情况。

    2.2 定义一个then变量等于x.then

    2.3 then是一个函数。使用call方法绑定x对象,传入解决回调函数拒绝回调函数作为参数。同时利用called变量记录then.call参数中两个回调函数的调用情况。

    2.4 then不是函数。调用resolve方法解决Promise,其参数为x

    2.5 对以上 2.2 检索属性和 2.3 调用方法的操作放在一起做容错处理。catch错误作为reject方法参数执行。同样利用called变量记录then.call参数中两个回调函数的调用情况。

  3. 如果x都没有出现以上两种状况:

    调用resolve方法解决Promise,其参数为x

// 2.3 Promise解决程序
function resolvePromise(p2, x, resolve, reject) {
    if (x === p2) {
        // 2.3.1 如果promise和x引用同一个对象
        reject(new TypeError())
    } else if ((x !== null && typeof x === 'object') || typeof x === 'function') {
        // 2.3.2 如果x是一个promise
        // 2.3.3 如果x是一个对象或函数
        let called
        try {
            let then = x.then // 检索x.then属性,做容错处理
            if (typeof then === 'function') {
                then.call(x, // 使用call绑定会立即执行then方法,做容错处理
                    (y) => { // y也可能是一个Promise,递归调用直到y被resolve或reject
                        if (called) { return }
                        called = true
                        resolvePromise(p2, y, resolve, reject)
                    },
                    (r) => {
                        if (called) { return }
                        called = true
                        reject(r)
                    }
                )
            } else {
                resolve(x)
            }
        } catch (e) {
            if (called) { return }
            called = true
            reject(e)
        }
    } else {
        resolve(x)
    }
}

called变量的作用:记录then.call传入参数(两个回调函数)的调用情况

根据Promise A+ 2.3.3.3.3规范:两个参数作为函数第一次调用优先,以后的调用都会被忽略。

因此我们在以上两个回调函数中这样处理:

  1. 已经调用过一次:此时called已经为true,直接return忽略
  2. 首次调用:此时calledundefined,调用后called设为true

注意:2.3 中的catch可能会发生(两个回调函数)已经调用但出现错误的情况,因此同样按上述说明处理。


运行官方测试用例

在完成上面的代码后,我们最终整合如下:

class myPromise {
    constructor(func) {
        this.state = 'pending'
        this.value = undefined
        this.reason = undefined
        this.resolveCallbacks = []
        this.rejectCallbacks = []
        try {
            func(this.resolve, this.reject)
        } catch (e) {
            this.reject(e)
        }
    }
    resolve = (value) => {
        if (this.state === 'pending') {
            this.state = 'fulfilled'
            this.value = value
            while (this.resolveCallbacks.length > 0) {
                this.resolveCallbacks.shift().call(undefined)
            }
        }
    }
    reject = (reason) => {
        if (this.state === 'pending') {
            this.state = 'rejected'
            this.reason = reason
            while (this.rejectCallbacks.length > 0) {
                this.rejectCallbacks.shift().call(undefined)
            }
        }
    }
    then(onFulfilled, onRejected) {
        onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : value => value
        onRejected = typeof onRejected === 'function' ? onRejected : reason => { throw reason }
        const p2 = new myPromise((resolve, reject) => {
            if (this.state === 'rejected') {
                queueMicrotask(() => {
                    try {
                        const x = onRejected(this.reason)
                        resolvePromise(p2, x, resolve, reject)
                    } catch (e) {
                        reject(e)
                    }
                })
            } else if (this.state === 'fulfilled') {
                queueMicrotask(() => {
                    try {
                        const x = onFulfilled(this.value)
                        resolvePromise(p2, x, resolve, reject)
                    } catch (e) {
                        reject(e)
                    }
                })
            } else if (this.state === 'pending') {
                this.resolveCallbacks.push(() => {
                    queueMicrotask(() => {
                        try {
                            const x = onFulfilled(this.value)
                            resolvePromise(p2, x, resolve, reject)
                        } catch (e) {
                            reject(e)
                        }
                    })
                })
                this.rejectCallbacks.push(() => {
                    queueMicrotask(() => {
                        try {
                            const x = onRejected(this.reason)
                            resolvePromise(p2, x, resolve, reject)
                        } catch (e) {
                            reject(e)
                        }
                    })
                })
            }
        })
        return p2
    }
}
function resolvePromise(p2, x, resolve, reject) {
    if (x === p2) {
        reject(new TypeError())
    } else if ((x !== null && typeof x === 'object') || typeof x === 'function') {
        let called
        try {
            let then = x.then
            if (typeof then === 'function') {
                then.call(x,
                    (y) => {
                        if (called) { return }
                        called = true
                        resolvePromise(p2, y, resolve, reject)
                    },
                    (r) => {
                        if (called) { return }
                        called = true
                        reject(r)
                    }
                )
            } else {
                resolve(x)
            }
        } catch (e) {
            if (called) { return }
            called = true
            reject(e)
        }
    } else {
        resolve(x)
    }
}
// 新加入部分
myPromise.deferred = function () {
    let result = {};
    result.promise = new myPromise((resolve, reject) => {
        result.resolve = resolve;
        result.reject = reject;
    });
    return result;
}
module.exports = myPromise;

新建一个文件夹,放入我们的 myPromise.js 并在终端执行以下命令:

npm init -y
npm install promises-aplus-tests

package.json 文件修改如下:

{
  "name": "promise",
  "version": "1.0.0",
  "description": "",
  "main": "myPromise.js",
  "scripts": {
    "test": "promises-aplus-tests myPromise"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "promises-aplus-tests": "^2.1.2"
  }
}

开始测试我们的手写Promise,在终端执行以下命令即可:

npm test

Promise 其他方法补充

容错处理方法

Promise.prototype.catch()

catch(onRejected) {
    return this.then(undefined, onRejected)
}

Promise.prototype.finally()

finally(callback) {
    return this.then(
        value => {
            return myPromise.resolve(callback()).then(() => value)
        },
        reason => {
            return myPromise.resolve(callback()).then(() => { throw reason })
        }
    )
}

静态方法

Promise.resolve()

static resolve(value) {
    if (value instanceof myPromise) {
        return value  // 传入的参数为Promise实例对象,直接返回
    } else {
        return new myPromise((resolve, reject) => {
            resolve(value)
        })
    }
}

Promise.reject()

static reject(reason) {
    return new myPromise((resolve, reject) => {
        reject(reason)
    })
}

Promise.all()

static all(promises) {
    return new myPromise((resolve, reject) => {
        let countPromise = 0 // 记录传入参数是否为Promise的次数
        let countResolve = 0 // 记录数组中每个Promise被解决次数
        let result = [] // 存储每个Promise的解决或拒绝的值
        if (promises.length === 0) { // 传入的参数是一个空的可迭代对象
            resolve(promises)
        }
        promises.forEach((element, index) => {
            if (element instanceof myPromise === false) { // 传入的参数不包含任何 promise
                ++countPromise
                if (countPromise === promises.length) {
                    queueMicrotask(() => {
                        resolve(promises)
                    })
                }
            } else {
                element.then(
                    value => {
                        ++countResolve
                        result[index] = value
                        if (countResolve === promises.length) {
                            resolve(result)
                        }
                    },
                    reason => {
                        reject(reason)
                    }
                )
            }
        })
    })
}

Promise.race()

static race(promises) {
    return new myPromise((resolve, reject) => {
        if (promises.length !== 0) {
            promises.forEach(element => {
                if (element instanceof myPromise === true)
                    element.then(
                        value => {
                            resolve(value)
                        },
                        reason => {
                            reject(reason)
                        }
                    )
            })
        }
    })
}

上述所有实现代码已放置我的Github仓库。可自行下载测试,做更多优化。

[ https://github.com/chscript/mypromise ]


参考

MDN-Promise

[译]Promise/A+ 规范

有关手写Promise方法(实现Promise A+规范)的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  3. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  4. ruby - Facter::Util::Uptime:Module 的未定义方法 get_uptime (NoMethodError) - 2

    我正在尝试设置一个puppet节点,但ruby​​gems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由ruby​​gems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby

  5. Ruby 方法() 方法 - 2

    我想了解Ruby方法methods()是如何工作的。我尝试使用“ruby方法”在Google上搜索,但这不是我需要的。我也看过ruby​​-doc.org,但我没有找到这种方法。你能详细解释一下它是如何工作的或者给我一个链接吗?更新我用methods()方法做了实验,得到了这样的结果:'labrat'代码classFirstdeffirst_instance_mymethodenddefself.first_class_mymethodendendclassSecond使用类#returnsavailablemethodslistforclassandancestorsputsSeco

  6. ruby-on-rails - Rails 3.2.1 中 ActionMailer 中的未定义方法 'default_content_type=' - 2

    我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer

  7. ruby - Highline 询问方法不会使用同一行 - 2

    设置:狂欢ruby1.9.2高线(1.6.13)描述:我已经相当习惯在其他一些项目中使用highline,但已经有几个月没有使用它了。现在,在Ruby1.9.2上全新安装时,它似乎不允许在同一行回答提示。所以以前我会看到类似的东西:require"highline/import"ask"Whatisyourfavoritecolor?"并得到:Whatisyourfavoritecolor?|现在我看到类似的东西:Whatisyourfavoritecolor?|竖线(|)符号是我的终端光标。知道为什么会发生这种变化吗? 最佳答案

  8. ruby - 主要 :Object when running build from sublime 的未定义方法 `require_relative' - 2

    我已经从我的命令行中获得了一切,所以我可以运行rubymyfile并且它可以正常工作。但是当我尝试从sublime中运行它时,我得到了undefinedmethod`require_relative'formain:Object有人知道我的sublime设置中缺少什么吗?我正在使用OSX并安装了rvm。 最佳答案 或者,您可以只使用“require”,它应该可以正常工作。我认为“require_relative”仅适用于ruby​​1.9+ 关于ruby-主要:Objectwhenrun

  9. ruby - 多个属性的 update_column 方法 - 2

    我有一个具有一些属性的模型:attr1、attr2和attr3。我需要在不执行回调和验证的情况下更新此属性。我找到了update_column方法,但我想同时更新三个属性。我需要这样的东西:update_columns({attr1:val1,attr2:val2,attr3:val3})代替update_column(attr1,val1)update_column(attr2,val2)update_column(attr3,val3) 最佳答案 您可以使用update_columns(attr1:val1,attr2:val2

  10. ruby - 检查方法参数的类型 - 2

    我不确定传递给方法的对象的类型是否正确。我可能会将一个字符串传递给一个只能处理整数的函数。某种运行时保证怎么样?我看不到比以下更好的选择:defsomeFixNumMangler(input)raise"wrongtype:integerrequired"unlessinput.class==FixNumother_stuffend有更好的选择吗? 最佳答案 使用Kernel#Integer在使用之前转换输入的方法。当无法以任何合理的方式将输入转换为整数时,它将引发ArgumentError。defmy_method(number)

随机推荐