{"id":21182226,"url":"https://github.com/chscript/mypromise","last_synced_at":"2025-09-11T23:37:33.728Z","repository":{"id":152506621,"uuid":"581131023","full_name":"chscript/mypromise","owner":"chscript","description":"💯 Implement the promise method and pass all official test cases","archived":false,"fork":false,"pushed_at":"2023-03-05T09:35:57.000Z","size":27,"stargazers_count":2,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-03-14T19:50:36.976Z","etag":null,"topics":["javascript","promise"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/chscript.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2022-12-22T11:00:42.000Z","updated_at":"2023-03-15T17:33:16.000Z","dependencies_parsed_at":null,"dependency_job_id":"7d680609-5ff4-44d0-9c66-157cafb6e241","html_url":"https://github.com/chscript/mypromise","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/chscript/mypromise","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/chscript%2Fmypromise","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/chscript%2Fmypromise/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/chscript%2Fmypromise/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/chscript%2Fmypromise/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/chscript","download_url":"https://codeload.github.com/chscript/mypromise/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/chscript%2Fmypromise/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":274726844,"owners_count":25338396,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-09-11T02:00:13.660Z","response_time":74,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["javascript","promise"],"created_at":"2024-11-20T17:56:09.051Z","updated_at":"2025-09-11T23:37:33.681Z","avatar_url":"https://github.com/chscript.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# 手写Promise\n\n## Promise 构造函数\n\n我们首先实现 Promise 的构造函数。需要处理的情况如下：\n\n1. Promise 状态记录：`this.state`\n2. 记录成功或失败的值：`this.value`和`this.reason`\n3. 收集解决和拒绝回调函数：`this.resolveCallbacks`和`this.rejectCallbacks`\n4. 执行首次传入的解决和拒绝回调函数：`func(this.resolve, this.reject)`\n\n```javascript\nclass myPromise {\n    constructor(func) {\n        this.state = 'pending' // Promise状态\n        this.value = undefined // 成功的值\n        this.reason = undefined // 失败的值\n        this.resolveCallbacks = [] // 收集解决回调函数\n        this.rejectCallbacks = [] // 收集拒绝回调函数\n        try { // 对传入的函数进行try...catch...做容错处理\n            func(this.resolve, this.reject) // 执行首次传入的两个回调函数\n        } catch (e) {\n            this.reject(e)\n        }\n    }\n}\n```\n\n## 三个状态（pending、rejected和fulfilled）\n\n`pending`：待定状态。待定`Promise`。只有在`then`方法执行后才会保持此状态。\n\n`fulfilled`：解决状态。终止`Promise`。只有在`resolve`方法执行后才会由`pending`更改为此状态。\n\n`rejected`：拒绝状态。终止`Promise`。只有在`reject`方法执行后才会由`pending`更改为此状态。\n\n**注意：其中只有`pedding`状态可以变更为`rejected`或`fulfilled`。`rejected`或`fulfilled`不能更改其他任何状态。**\n\n## 三个方法（resolve、reject和then）\n\n### `resolve`方法实现要点\n\n1. 状态由`pending`为`fulfilled。`\n2. `resolve`方法传入的`value`参数赋值给`this.value`\n3. 按顺序执行`resolveCallbacks`里面所有解决回调函数\n4. 利用`call`方法将解决回调函数内部的`this`绑定为`undefined`\n\n**坑点 1**：`resolve`方法内部`this`指向会丢失，进而造成`this.value`丢失。\n\n**解决办法**：我们将`resolve`方法定义为箭头函数。在构造函数执行后，箭头函数可以绑定实例对象的`this`指向。\n\n```javascript\n// 2.1. Promise 状态\nresolve = (value) =\u003e { // 在执行构造函数时内部的this通过箭头函数绑定实例对象\n    if (this.state === 'pending') {\n        this.state = 'fulfilled' // 第一点\n        this.value = value // 第二点\n        while (this.resolveCallbacks.length \u003e 0) { // 第三点\n            this.resolveCallbacks.shift().call(undefined) // 第四点\n        }\n    }\n}\n```\n\n### `reject`方法实现要点\n\n1. 状态由`pending`为`rejected`\n2. `reject`方法传入的`reason`参数赋值给`this.reason`\n3. 按顺序执行`rejectCallbacks`里面所有拒绝回调函数\n4. 利用`call`方法将拒绝回调函数内部的`this`绑定为`undefined`\n\n**坑点 1**： `reject` 方法内部`this`指向会丢失，进而造成`this.reason`丢失。\n\n**解决办法**：我们将`reject`方法定义为箭头函数。在构造函数执行后，箭头函数可以绑定实例对象的`this`指向。\n\n```javascript\n// 2.1. Promise 状态\nreject = (reason) =\u003e { // 在执行构造函数时内部的this通过箭头函数绑定实例对象\n    if (this.state === 'pending') {\n        this.state = 'rejected' // 第一点\n        this.reason = reason // 第二点\n        while (this.rejectCallbacks.length \u003e 0) {  // 第三点\n            this.rejectCallbacks.shift().call(undefined) // 第四点\n        }\n    }\n}\n```\n\n### `then`方法实现要点\n\n1. 判断then方法的两个参数`onRejected`和`onFulfilled`是否为`function`。\n\n    1.1 `onRejected`和`onFulfilled`都是`function`，继续执行下一步。\n\n    1.2 `onRejected`不是`function`，将`onRejected`赋值为箭头函数，参数为`reason`执行`throw reason`\n\n    1.3 `onFulfilled`不是`function`，将`onFulfilled`赋值为箭头函数，参数为`value`执行`return value`\n\n2. 当前Promise状态为**rejected**：\n\n    2.1 `onRejected`方法传入`this.reason`参数，异步执行。\n\n    2.2 对执行的`onRejected`方法做容错处理，`catch`错误作为`reject`方法参数执行。\n\n3. 当前Promise状态为**fulfilled**：\n\n    3.1 `onFulfilled`方法传入`this.value`参数，异步执行。\n\n    3.2 对执行的`onFulfilled`方法做容错处理，`catch`错误作为`reject`方法参数执行。\n\n4. 当前Promise状态为**pending**：\n\n    4.1 收集`onFulfilled`和`onRejected`两个回调函数分别`push`给`resolveCallbacks`和`rejectCallbacks`。\n\n    4.2 收集的回调函数同样如上所述，**先做异步执行再做容错处理**。\n\n5. 返回一个 Promise 实例对象。\n\n```javascript\n// 2.2. then 方法\nthen(onFulfilled, onRejected) {\n    onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : value =\u003e value // 第一点 \n    onRejected = typeof onRejected === 'function' ? onRejected : reason =\u003e { throw reason } // 第一点 \n    const p2 = new myPromise((resolve, reject) =\u003e {\n        if (this.state === 'rejected') { // 第二点\n            queueMicrotask(() =\u003e {\n                try {\n                    onRejected(this.reason)\n                } catch (e) {\n                    reject(e)\n                }\n            })\n        } else if (this.state === 'fulfilled') { // 第三点\n            queueMicrotask(() =\u003e {\n                try {\n                    onFulfilled(this.value)\n                } catch (e) {\n                    reject(e)\n                }\n            })\n        } else if (this.state === 'pending') { // 第四点\n            this.resolveCallbacks.push(() =\u003e {\n                queueMicrotask(() =\u003e {\n                    try {\n                        onFulfilled(this.value)\n                    } catch (e) {\n                        reject(e)\n                    }\n                })\n            })\n            this.rejectCallbacks.push(() =\u003e {\n                queueMicrotask(() =\u003e {\n                    try {\n                        onRejected(this.reason)\n                    } catch (e) {\n                        reject(e)\n                    }\n                })\n            })\n        }\n    })\n    return p2 // 第五点\n}\n```\n\n## Promise 解决程序（resolvePromise方法）\n\n旁白：其实这个解决程序才是实现核心Promise最难的一部分。因为Promise A+规范对于这部分说的比较绕。\n\n我们直击其实现要点，能跑通所有官方用例就行。如下：\n\n1. 如果x和promise引用同一个对象：\n\n    1.1 调用`reject`方法，其参数为`new TypeError()`\n\n2. 如果x是一个promise或x是一个对象或函数：\n\n    2.1 定义一个`called`变量用于记录`then.call`参数中两个回调函数的调用情况。\n\n    2.2 定义一个`then`变量等于`x.then`\n\n    2.3 `then`是一个函数。使用`call`方法绑定`x`对象，传入**解决回调函数**和**拒绝回调函数**作为参数。同时利用`called`变量记录`then.call`参数中两个回调函数的调用情况。\n\n    2.4 `then`不是函数。调用`resolve`方法解决Promise，其参数为`x`\n\n    2.5 对以上 **2.2** 检索属性和 **2.3** 调用方法的操作放在一起做容错处理。`catch`错误作为`reject`方法参数执行。同样利用`called`变量记录`then.call`参数中两个回调函数的调用情况。\n\n3. 如果x都没有出现以上两种状况：\n\n    调用`resolve`方法解决Promise，其参数为`x`\n\n```javascript\n// 2.3 Promise解决程序\nfunction resolvePromise(p2, x, resolve, reject) {\n    if (x === p2) {\n        // 2.3.1 如果promise和x引用同一个对象\n        reject(new TypeError())\n    } else if ((x !== null \u0026\u0026 typeof x === 'object') || typeof x === 'function') {\n        // 2.3.2 如果x是一个promise\n        // 2.3.3 如果x是一个对象或函数\n        let called\n        try {\n            let then = x.then // 检索x.then属性，做容错处理\n            if (typeof then === 'function') {\n                then.call(x, // 使用call绑定会立即执行then方法，做容错处理\n                    (y) =\u003e { // y也可能是一个Promise，递归调用直到y被resolve或reject\n                        if (called) { return }\n                        called = true\n                        resolvePromise(p2, y, resolve, reject)\n                    },\n                    (r) =\u003e {\n                        if (called) { return }\n                        called = true\n                        reject(r)\n                    }\n                )\n            } else {\n                resolve(x)\n            }\n        } catch (e) {\n            if (called) { return }\n            called = true\n            reject(e)\n        }\n    } else {\n        resolve(x)\n    }\n}\n```\n\n`called`变量的作用：**记录**`then.call`传入参数（两个回调函数）的**调用情况**。\n\n根据**Promise A+ 2.3.3.3.3**规范：两个参数作为函数第一次调用优先，以后的调用都会被忽略。\n\n因此我们在以上两个回调函数中这样处理：\n\n1. **已经调用过一次**：此时`called`已经为true，直接`return`忽略\n2. **首次调用**：此时`called`为`undefined`，调用后`called`设为`true`\n\n**注意：2.3 中的`catch`可能会发生（两个回调函数）已经调用但出现错误的情况，因此同样按上述说明处理。**\n\n## 运行官方测试用例\n\n在完成上面的代码后，我们最终整合如下：\n\n```javascript\nclass myPromise {\n    constructor(func) {\n        this.state = 'pending'\n        this.value = undefined\n        this.reason = undefined\n        this.resolveCallbacks = []\n        this.rejectCallbacks = []\n        try {\n            func(this.resolve, this.reject)\n        } catch (e) {\n            this.reject(e)\n        }\n    }\n    resolve = (value) =\u003e {\n        if (this.state === 'pending') {\n            this.state = 'fulfilled'\n            this.value = value\n            while (this.resolveCallbacks.length \u003e 0) {\n                this.resolveCallbacks.shift().call(undefined)\n            }\n        }\n    }\n    reject = (reason) =\u003e {\n        if (this.state === 'pending') {\n            this.state = 'rejected'\n            this.reason = reason\n            while (this.rejectCallbacks.length \u003e 0) {\n                this.rejectCallbacks.shift().call(undefined)\n            }\n        }\n    }\n    then(onFulfilled, onRejected) {\n        onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : value =\u003e value\n        onRejected = typeof onRejected === 'function' ? onRejected : reason =\u003e { throw reason }\n        const p2 = new myPromise((resolve, reject) =\u003e {\n            if (this.state === 'rejected') {\n                queueMicrotask(() =\u003e {\n                    try {\n                        const x = onRejected(this.reason)\n                        resolvePromise(p2, x, resolve, reject)\n                    } catch (e) {\n                        reject(e)\n                    }\n                })\n            } else if (this.state === 'fulfilled') {\n                queueMicrotask(() =\u003e {\n                    try {\n                        const x = onFulfilled(this.value)\n                        resolvePromise(p2, x, resolve, reject)\n                    } catch (e) {\n                        reject(e)\n                    }\n                })\n            } else if (this.state === 'pending') {\n                this.resolveCallbacks.push(() =\u003e {\n                    queueMicrotask(() =\u003e {\n                        try {\n                            const x = onFulfilled(this.value)\n                            resolvePromise(p2, x, resolve, reject)\n                        } catch (e) {\n                            reject(e)\n                        }\n                    })\n                })\n                this.rejectCallbacks.push(() =\u003e {\n                    queueMicrotask(() =\u003e {\n                        try {\n                            const x = onRejected(this.reason)\n                            resolvePromise(p2, x, resolve, reject)\n                        } catch (e) {\n                            reject(e)\n                        }\n                    })\n                })\n            }\n        })\n        return p2\n    }\n}\nfunction resolvePromise(p2, x, resolve, reject) {\n    if (x === p2) {\n        reject(new TypeError())\n    } else if ((x !== null \u0026\u0026 typeof x === 'object') || typeof x === 'function') {\n        let called\n        try {\n            let then = x.then\n            if (typeof then === 'function') {\n                then.call(x,\n                    (y) =\u003e {\n                        if (called) { return }\n                        called = true\n                        resolvePromise(p2, y, resolve, reject)\n                    },\n                    (r) =\u003e {\n                        if (called) { return }\n                        called = true\n                        reject(r)\n                    }\n                )\n            } else {\n                resolve(x)\n            }\n        } catch (e) {\n            if (called) { return }\n            called = true\n            reject(e)\n        }\n    } else {\n        resolve(x)\n    }\n}\n// 新加入部分\nmyPromise.deferred = function () {\n    let result = {};\n    result.promise = new myPromise((resolve, reject) =\u003e {\n        result.resolve = resolve;\n        result.reject = reject;\n    });\n    return result;\n}\nmodule.exports = myPromise;\n```\n\n新建一个文件夹，放入我们的 myPromise.js 并在终端执行以下命令：\n\n```shell\nnpm init -y\nnpm install promises-aplus-tests\n```\n\npackage.json 文件修改如下：\n\n```json\n{\n  \"name\": \"promise\",\n  \"version\": \"1.0.0\",\n  \"description\": \"\",\n  \"main\": \"myPromise.js\",\n  \"scripts\": {\n    \"test\": \"promises-aplus-tests myPromise\"\n  },\n  \"keywords\": [],\n  \"author\": \"\",\n  \"license\": \"ISC\",\n  \"devDependencies\": {\n    \"promises-aplus-tests\": \"^2.1.2\"\n  }\n}\n```\n\n开始测试我们的手写Promise，在终端执行以下命令即可：\n\n```shell\nnpm test\n```\n\n## Promise 其他方法补充\n\n### 容错处理方法\n\n**Promise.prototype.catch()**\n\n```javascript\ncatch(onRejected) {\n    return this.then(undefined, onRejected)\n}\n```\n\n**Promise.prototype.finally()**\n\n```javascript\nfinally(callback) {\n    return this.then(\n        value =\u003e {\n            return myPromise.resolve(callback()).then(() =\u003e value)\n        },\n        reason =\u003e {\n            return myPromise.resolve(callback()).then(() =\u003e { throw reason })\n        }\n    )\n}\n```\n\n### 静态方法\n\n**Promise.resolve()**\n\n```javascript\nstatic resolve(value) {\n    if (value instanceof myPromise) {\n        return value  // 传入的参数为Promise实例对象，直接返回\n    } else {\n        return new myPromise((resolve, reject) =\u003e {\n            resolve(value)\n        })\n    }\n}\n```\n\n**Promise.reject()**\n\n```javascript\nstatic reject(reason) {\n    return new myPromise((resolve, reject) =\u003e {\n        reject(reason)\n    })\n}\n```\n\n**Promise.all()**\n\n```javascript\nstatic all(promises) {\n    return new myPromise((resolve, reject) =\u003e {\n        let countPromise = 0 // 记录传入参数是否为Promise的次数\n        let countResolve = 0 // 记录数组中每个Promise被解决次数\n        let result = [] // 存储每个Promise的解决或拒绝的值\n        if (promises.length === 0) { // 传入的参数是一个空的可迭代对象\n            resolve(promises)\n        }\n        promises.forEach((element, index) =\u003e {\n            if (element instanceof myPromise === false) { // 传入的参数不包含任何 promise\n                ++countPromise\n                if (countPromise === promises.length) {\n                    queueMicrotask(() =\u003e {\n                        resolve(promises)\n                    })\n                }\n            } else {\n                element.then(\n                    value =\u003e {\n                        ++countResolve\n                        result[index] = value\n                        if (countResolve === promises.length) {\n                            resolve(result)\n                        }\n                    },\n                    reason =\u003e {\n                        reject(reason)\n                    }\n                )\n            }\n        })\n    })\n}\n```\n\n**Promise.race()**\n\n```javascript\nstatic race(promises) {\n    return new myPromise((resolve, reject) =\u003e {\n        if (promises.length !== 0) {\n            promises.forEach(element =\u003e {\n                if (element instanceof myPromise === true)\n                    element.then(\n                        value =\u003e {\n                            resolve(value)\n                        },\n                        reason =\u003e {\n                            reject(reason)\n                        }\n                    )\n            })\n        }\n    })\n}\n```\n\n上述所有实现代码已放置我的Github仓库。可自行下载测试，做更多优化。\n\n[ https://github.com/chscript/mypromise ]\n\n\n\n\u003e 参考\n\u003e\n\u003e [MDN-Promise ](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise)\n\u003e\n\u003e [[译]Promise/A+ 规范](https://zhuanlan.zhihu.com/p/143204897)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fchscript%2Fmypromise","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fchscript%2Fmypromise","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fchscript%2Fmypromise/lists"}