图解JavaScript——代码实现(六种异步方案,重点是Promise、Async、发布/订阅原理实现,真香)

{"type":"doc","content":[{"type":"blockquote","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"关注公众号“"},{"type":"text","marks":[{"type":"strong"}],"text":"执鸢者"},{"type":"text","text":"”,回复“"},{"type":"text","marks":[{"type":"strong"}],"text":"书籍"},{"type":"text","text":"”获取大量前端学习资料,回复“"},{"type":"text","marks":[{"type":"strong"}],"text":"前端视频"},{"type":"text","text":"”获取大量前端教学视频,回复“"},{"type":"text","marks":[{"type":"strong"}],"text":"异步"},{"type":"text","text":"”获取本节整体思维导图。"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/9a/9a3d2734b53d10fd2fd73b6e994d989d.jpeg","alt":null,"title":null,"style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"blockquote","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"本节主要阐述六种异步方案:回调函数、事件监听、发布/订阅、Promise、Generator和Async。其中重点是发布/订阅、Promise、Async的原理实现,通过对这几点的了解,希望我们前端切图仔能够在修炼内功的路上更进一步。"}]}]},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"一、六种异步方案"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/82/82414298af7c89bdc4359e32e3673bba.jpeg","alt":null,"title":null,"style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"1.1 回调函数"}]},{"type":"blockquote","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"异步编程的最基本方法,把任务的第二段单独写在一个函数里面,等到重新执行这个任务的时候,就直接调用这个函数。"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"bulletedlist","content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"优点:简单、容易理解和实现。"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"缺点:多次调用会使代码结构混乱,形成回调地狱。"}]}]}]},{"type":"codeblock","attrs":{"lang":""},"content":[{"type":"text","text":"function sleep(time, callback) {\n setTimeout(() => {\n // 一些逻辑代码\n callback();\n }, time);\n}"}]},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"1.2 事件监听"}]},{"type":"blockquote","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"异步任务的执行不取决于代码的执行顺序,而取决于某个事件是否发生。"}]}]},{"type":"bulletedlist","content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"优点:易于理解,此外对于每个事件可以指定多个回调函数,而且可以“去耦合”,有利于实现模块化。"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"缺点:整个程序都要变成事件驱动型,运行流程会变得很不清晰。"}]}]}]},{"type":"codeblock","attrs":{"lang":""},"content":[{"type":"text","text":"dom.addEventListener('click', () => {\n console.log('dom被点击后触发!!!');\n})"}]},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"1.3 发布/订阅"}]},{"type":"blockquote","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"发布/订阅模式在观察者模式的基础上,在目标和观察者之间增加一个调度中心。订阅者(观察者)把自己想要订阅的事件注册到调度中心,当该事件触发的时候,发布者(目标)发布该事件到调度中心,由调度中心统一调度订阅者注册到调度中心的处理代码。"}]}]},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"1.4 Promise"}]},{"type":"blockquote","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"Promise 是异步编程的一种解决方案,是为解决回调函数地狱这个问题而提出的,它不是新的语法功能,而是一种新的写法,允许将回调函数的嵌套改为链式调用。"}]}]},{"type":"bulletedlist","content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"优点:将回调函数的嵌套改为了链式调用;使用then方法以后,异步任务的两端执行看的更加清楚。"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"缺点:Promise 的最大问题是代码冗余,原来的任务被 Promise 包装了一下,不管什么操作,一眼看去都是一堆then,原来的语义变得很不清楚。"}]}]}]},{"type":"codeblock","attrs":{"lang":""},"content":[{"type":"text","text":"const promise = new Promise((resolve, reject) => {\n if (/*如果异步成功*/) {\n resolve(value);\n } else {\n reject(error);\n }\n});\n\npromise.then((value) => {\n // ...success\n}, (reason) => {\n // ...failure\n})"}]},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"1.5 Generator"}]},{"type":"blockquote","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"Generator 函数是ES6提供的一种异步编程解决方案,语法行为与传统函数完全不同。其最大特点是可以控制函数的执行。"}]}]},{"type":"bulletedlist","content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"优点:异步操作表示的很简洁,此外可以控制函数的执行。"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"缺点:流程管理不方便,不能实现自动化的流程管理。"}]}]}]},{"type":"codeblock","attrs":{"lang":""},"content":[{"type":"text","text":"function* genF() {\n yield 'come on!';\n yield 'Front End Engineer';\n return 'goood';\n}\n\nconst gF = genF();\ngF.next();// {value: \"come on!\", done: false}\ngF.next();// {value: \"Front End Engineer\", done: false}\ngF.next();// {value: \"goood\", done: true}\ngF.next();// {value: undefined, done: true}"}]},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"1.6 Async"}]},{"type":"blockquote","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"ES2017 标准引入了async函数,使得异步操作变得更加方便。简言之,该函数就是Generator函数的语法糖。"}]}]},{"type":"bulletedlist","content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"优点:内置执行器,可以自动执行;语义相比Generator更加清晰;返回值是Promise,比Generator函数的返回值是Iterator对象操作更加方便。"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"增加学习成本。"}]}]}]},{"type":"codeblock","attrs":{"lang":""},"content":[{"type":"text","text":"async function asyncFun() {\n await func1()\n \n await func2();\n \n return '666';\n}\nfunction func1() {\n return new Promise((resolve, reject) => {\n setTimeout(() => {\n resolve('888')\n }, 100);\n }).then((value) => {\n console.log(value);\n });\n}\n\nfunction func2() {\n return new Promise((resolve, reject) => {\n setTimeout(() => {\n resolve('777')\n });\n }).then((value) => {\n console.log(value);\n });\n}\n\nasyncFun().then((value) => {\n console.log(value);\n});\n// 888\n// 777\n// 666"}]},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"二、Promise原理实现"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":">不管是实际开发中还是面试过程中,各位老铁们对Promise肯定不会陌生,下面就让我们一起来唠一唠Promsie的实现原理,根据PromiseA+规范来进行实现,然后对其相关的静态方法(Promise.resolve()、Promise.reject()、Promise.all()、Promise.race())和实例方法(Promise.prototype.catch()、Promise.prototype.finally())进行实现。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/1b/1be6a0c9fd81bc625b19c76b39626c7f.jpeg","alt":null,"title":null,"style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"2.1 思考一下"}]},{"type":"blockquote","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"首先用一幅图来展示一下我考虑实现这个函数的思路吧。"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/eb/ebda7d2b879806ef8e219f85a3589452.jpeg","alt":null,"title":null,"style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"2.2 根据Promise/A+规范实现Promise"}]},{"type":"blockquote","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"人家有相关标准,我们就要遵守,毕竟遵纪守法才是好公民,现在只能硬着头皮把这个标准过一遍。"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/c8/c8b836dc65c1a8488e48c81bb4b700fd.jpeg","alt":null,"title":null,"style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"blockquote","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"下面就是基于Promise/A+规范实现的代码,已经经过promises-aplus-tests库进行了验证。"}]}]},{"type":"codeblock","attrs":{"lang":""},"content":[{"type":"text","text":"const PENDING = 'pending';\nconst FULFILLED = 'fulfilled';\nconst REJECTED = 'rejected';\n/**\n * Promise构造函数\n * excutor: 内部同步执行的函数\n */\nclass Promise {\n constructor(excutor) {\n const self = this;\n self.status = PENDING;\n self.onFulfilled = [];// 成功的回调\n self.onRejected = [];// 失败的回调\n\n // 异步处理成功调用的函数\n // PromiseA+ 2.1 状态只能由Pending转为fulfilled或rejected;fulfilled状态必须有一个value值;rejected状态必须有一个reason值。\n function resolve(value) {\n if (self.status === PENDING) {\n self.status = FULFILLED;\n self.value = value;\n // PromiseA+ 2.2.6.1 相同promise的then可以被调用多次,当promise变为fulfilled状态,全部的onFulfilled回调按照原始调用then的顺序执行\n self.onFulfilled.forEach(fn => fn());\n }\n }\n\n function reject(reason) {\n if (self.status === PENDING) {\n self.status = REJECTED;\n self.reason = reason;\n // PromiseA+ 2.2.6.2 相同promise的then可以被调用多次,当promise变为rejected状态,全部的onRejected回调按照原始调用then的顺序执行\n self.onRejected.forEach(fn => fn());\n }\n }\n\n try {\n excutor(resolve, reject);\n } catch (e) {\n reject(e);\n }\n }\n\n then(onFulfilled, onRejected) {\n // PromiseA+ 2.2.1 onFulfilled和onRejected是可选参数\n // PromiseA+ 2.2.5 onFulfilled和onRejected必须被作为函数调用\n // PromiseA+ 2.2.7.3 如果onFulfilled不是函数且promise1状态是fulfilled,则promise2有相同的值且也是fulfilled状态\n // PromiseA+ 2.2.7.4 如果onRejected不是函数且promise1状态是rejected,则promise2有相同的值且也是rejected状态\n onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : value => value;\n onRejected = typeof onRejected === 'function' ? onRejected : reason => { throw reason };\n\n const self = this;\n const promise = new Promise((resolve, reject) => {\n const handle = (callback, data) => {\n // PromiseA+ 2.2.4 onFulfilled或者onRejected需要在自己的执行上下文栈里被调用,所以此处用setTimeout\n setTimeout(() => {\n try {\n // PromiseA+ 2.2.2 如果onFulfilled是函数,则在fulfilled状态之后调用,第一个参数为value\n // PromiseA+ 2.2.3 如果onRejected是函数,则在rejected状态之后调用,第一个参数为reason\n const x = callback(data);\n // PromiseA+ 2.2.7.1 如果onFulfilled或onRejected返回一个x值,运行这[[Resolve]](promise2, x)\n resolvePromise(promise, x, resolve, reject);\n } catch (e) {\n // PromiseA+ 2.2.7.2 onFulfilled或onRejected抛出一个异常e,promise2必须以e的理由失败\n reject(e);\n }\n })\n }\n if (self.status === PENDING) {\n self.onFulfilled.push(() => {\n handle(onFulfilled, self.value);\n });\n\n self.onRejected.push(() => {\n handle(onRejected, self.reason);\n })\n } else if (self.status === FULFILLED) {\n setTimeout(() => {\n handle(onFulfilled, self.value);\n })\n } else if (self.status === REJECTED) {\n setTimeout(() => {\n handle(onRejected, self.reason);\n })\n }\n })\n\n return promise;\n }\n}\n\nfunction resolvePromise(promise, x, resolve, reject) {\n // PromiseA+ 2.3.1 如果promise和x引用同一对象,会以TypeError错误reject promise\n if (promise === x) {\n reject(new TypeError('Chaining Cycle'));\n }\n\n if (x && typeof x === 'object' || typeof x === 'function') {\n // PromiseA+ 2.3.3.3.3 如果resolvePromise和rejectPromise都被调用,或者对同一个参数进行多次调用,那么第一次调用优先,以后的调用都会被忽略。 \n let used;\n try {\n // PromiseA+ 2.3.3.1 let then be x.then\n // PromiseA+ 2.3.2 调用then方法已经包含了该条(该条是x是promise的处理)。\n let then = x.then;\n\n if (typeof then === 'function') {\n // PromiseA+ 2.3.3.3如果then是一个函数,用x作为this调用它。第一个参数是resolvePromise,第二个参数是rejectPromise\n // PromiseA+ 2.3.3.3.1 如果resolvePromise用一个值y调用,运行[[Resolve]](promise, y)\n // PromiseA+ 2.3.3.3.2 如果rejectPromise用一个原因r调用,用r拒绝promise。\n then.call(x, (y) => {\n if (used) return;\n used = true;\n resolvePromise(promise, y, resolve, reject)\n }, (r) => {\n if (used) return;\n used = true;\n reject(r);\n })\n } else {\n // PromiseA+ 如果then不是一个函数,变为fulfilled状态并传值为x\n if (used) return;\n used = true;\n resolve(x);\n }\n } catch (e) {\n // PromiseA+ 2.3.3.2 如果检索属性x.then抛出异常e,则以e为原因拒绝promise\n // PromiseA+ 2.3.3.4 如果调用then抛出异常,但是resolvePromise或rejectPromise已经执行,则忽略它\n if (used) return;\n used = true;\n reject(e);\n }\n\n } else {\n // PromiseA+ 2.3.4 如果x不是一个对象或函数,状态变为fulfilled并传值x\n resolve(x);\n }\n}"}]},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"2.2 其他方法"}]},{"type":"blockquote","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"按照Promise/A+规范实现了Promise的核心内容,但是其只实现了Promise.prototype.then()方法,那其它方法呢?下面我们就唠一唠其它方法,包括静态方法(Promise.resolve()、Promise.reject()、Promise.all()、Promise.race())和实例方法(Promise.prototype.catch()、Promise.prototype.finally())。"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/e2/e23156c0f6bd22d7d2b8ac9b8cc14220.jpeg","alt":null,"title":null,"style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"heading","attrs":{"align":null,"level":4},"content":[{"type":"text","text":"2.2.1 Promise.resolve()"}]},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/36/36c149240b8a3b4580f68fc8d0c21554.jpeg","alt":null,"title":null,"style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":""},"content":[{"type":"text","text":"class Promise {\n // ...\n // 将现有对象转为 Promise 对象\n static resolve(value) {\n // 如果参数是 Promise 实例,那么Promise.resolve将不做任何修改、原封不动地返回这个实例。\n if (value instanceof Promise) return value;\n\n // 参数是一个thenable对象(具有then方法的对象),Promise.resolve方法会将这个对象转为 Promise 对象,然后就立即执行thenable对象的then方法。\n if (typeof value === 'object' || typeof value === 'function') {\n try {\n let then = value.then;\n if (typeof then === 'function') {\n return new Promise(then.bind(value));\n }\n } catch (e) {\n return new Promise((resolve, reject) => {\n reject(e);\n })\n }\n }\n\n // 参数不是具有then方法的对象,或根本就不是对象,Promise.resolve方法返回一个新的 Promise 对象,状态为resolved。\n return new Promise((resolve, reject) => {\n resolve(value);\n })\n }\n}"}]},{"type":"heading","attrs":{"align":null,"level":4},"content":[{"type":"text","text":"2.2.2 Promise.reject()"}]},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/71/71936987eeebc38a0230ed0eb43cfbeb.jpeg","alt":null,"title":null,"style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":""},"content":[{"type":"text","text":"class Promise {\n // ...\n // 返回一个新的 Promise 实例,该实例的状态为rejected。\n static reject(reason) {\n return new Promise((resolve, reject) => {\n reject(reason);\n })\n }\n}"}]},{"type":"heading","attrs":{"align":null,"level":4},"content":[{"type":"text","text":"2.2.3 Promise.all()"}]},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/35/35241eff0dc14099507b7a72cf1da63c.jpeg","alt":null,"title":null,"style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":""},"content":[{"type":"text","text":"class Promise {\n // ...\n // 用于将多个 Promise 实例,包装成一个新的 Promise 实例。只有所有状态都变为fulfilled,p的状态才会是fulfilled\n static all(promises) {\n const values = [];\n let resolvedCount = 0;\n return new Promise((resolve, reject) => {\n promises.forEach((p, index) => {\n Promise.resolve(p).then(value => {\n resolvedCount++;\n values[index] = value;\n if (resolvedCount === promises.length) {\n resolve(values);\n }\n }, reason => {\n reject(reason);\n })\n })\n })\n }\n}"}]},{"type":"heading","attrs":{"align":null,"level":4},"content":[{"type":"text","text":"2.2.4 Promise.race()"}]},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/81/8113cf0fcb751e581a0437e20c4def91.jpeg","alt":null,"title":null,"style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":""},"content":[{"type":"text","text":"class Promise {\n // ...\n // 只要有一个实例率先改变状态,状态就跟着改变。那个率先改变的 Promise 实例的返回值,就传递给回调函数。\n static race(promises) {\n return new Promise((resolve, reject) => {\n promises.forEach((p, index) => {\n Promise.resolve(p).then(value => {\n resolve(value);\n }, reason => {\n reject(reason);\n })\n })\n })\n }\n}"}]},{"type":"heading","attrs":{"align":null,"level":4},"content":[{"type":"text","text":"2.2.5 Promise.catch()"}]},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/e0/e018e951b2c0a876869b69393b0578cd.jpeg","alt":null,"title":null,"style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":""},"content":[{"type":"text","text":"class Promise {\n // ...\n // 是.then(null, rejection)或.then(undefined, rejection)的别名,用于指定发生错误时的回调函数。\n catch(onRejected) {\n return this.then(undefined, onRejected);\n }\n}"}]},{"type":"heading","attrs":{"align":null,"level":4},"content":[{"type":"text","text":"2.2.6 Promise.finally()"}]},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/5f/5fb8a08a8fb7c32ffa8ceb4d44d1bb30.jpeg","alt":null,"title":null,"style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":""},"content":[{"type":"text","text":"class Promise {\n // ...\n // 用于指定不管 Promise 对象最后状态如何,都会执行的操作。\n finally(callback) {\n return this.then(\n value => Promise.resolve(callback()).then(() => value),\n reason => Promise.resolve(callback()).then(() => { throw reason })\n )\n }\n}"}]},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"三、Async原理实现"}]},{"type":"blockquote","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"在开发过程中常用的另一种异步方案莫过于Async,通过async函数的引入使得异步操作变得更加方便。实质上,async是Generator的语法糖,最大的亮点是async内置执行器,调用后即可自动执行,不像Generator需要调用next()方法才能执行。"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/c4/c42bf4c537f0997097363e06b2acb976.jpeg","alt":null,"title":null,"style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"blockquote","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"这是Async的实现原理,即将Generator函数作为参数放入run函数中,最终实现自动执行并返回Promise对象。"}]}]},{"type":"codeblock","attrs":{"lang":""},"content":[{"type":"text","text":"function run(genF) {\n // 返回值是Promise\n return new Promise((resolve, reject) => {\n const gen = genF();\n function step(nextF) {\n let next;\n try {\n // 执行该函数,获取一个有着value和done两个属性的对象\n next = nextF();\n } catch (e) {\n // 出现异常则将该Promise变为rejected状态\n reject(e);\n }\n\n // 判断是否到达末尾,Generator函数到达末尾则将该Promise变为fulfilled状态\n if (next.done) {\n return resolve(next.value);\n }\n\n // 没到达末尾,则利用Promise封装该value,直到执行完毕,反复调用step函数,实现自动执行\n Promise.resolve(next.value).then((v) => {\n step(() => gen.next(v))\n }, (e) => {\n step(() => gen.throw(e))\n })\n }\n\n step(() => gen.next(undefined));\n })\n}"}]},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"四、发布/订阅实现"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"更加详细内容可以参考"},{"type":"link","attrs":{"href":"https://mp.weixin.qq.com/s/GzPqSgna9Fwqal-5Oyg5EA","title":""},"content":[{"type":"text","text":"《图解23种设计模式》"}]}]},{"type":"blockquote","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"发布/订阅模式在观察者模式的基础上,在目标和观察者之间增加一个调度中心。订阅者(观察者)把自己想要订阅的事件注册到调度中心,当该事件触发的时候,发布者(目标)发布该事件到调度中心,由调度中心统一调度订阅者注册到调度中心的处理代码。"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/4e/4e30a5b625d4623afa639f8f85fa247c.png","alt":null,"title":null,"style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":""},"content":[{"type":"text","text":"// 发布订阅(TypeScript版)\ninterface Publish {\n registerObserver(eventType : string, subscribe : Subscribe) : void;\n remove(eventType : string, subscribe ?: Subscribe) : void;\n notifyObservers(eventType : string) : void;\n}\ninterface SubscribesObject{\n [key : string] : Array\n}\nclass ConcretePublish implements Publish {\n private subscribes : SubscribesObject;\n\n constructor() {\n this.subscribes = {};\n }\n\n registerObserver(eventType : string, subscribe : Subscribe) : void {\n if (!this.subscribes[eventType]) {\n this.subscribes[eventType] = [];\n }\n\n this.subscribes[eventType].push(subscribe);\n }\n\n remove(eventType : string, subscribe ?: Subscribe) : void {\n const subscribeArray = this.subscribes[eventType];\n if (subscribeArray) {\n if (!subscribe) {\n delete this.subscribes[eventType];\n } else {\n for (let i = 0; i < subscribeArray.length; i++) {\n if (subscribe === subscribeArray[i]) {\n subscribeArray.splice(i, 1);\n }\n }\n }\n }\n }\n\n notifyObservers(eventType : string, ...args : any[]) : void {\n const subscribes = this.subscribes[eventType];\n if (subscribes) {\n subscribes.forEach(subscribe => subscribe.update(...args))\n }\n }\n}\n\ninterface Subscribe {\n update(...value : any[]) : void;\n}\n\nclass ConcreteSubscribe1 implements Subscribe {\n public update(...value : any[]) : void {\n console.log('已经执行更新操作1,值为', ...value);\n }\n}\nclass ConcreteSubscribe2 implements Subscribe {\n public update(...value : any[]) : void {\n console.log('已经执行更新操作2,值为', ...value);\n }\n}\n\nfunction main() {\n const publish = new ConcretePublish();\n const subscribe1 = new ConcreteSubscribe1();\n const subscribe2 = new ConcreteSubscribe2();\n\n publish.registerObserver('1', subscribe1);\n publish.registerObserver('2', subscribe2);\n\n publish.notifyObservers('2', '22222');\n}\n\nmain();\n"}]},{"type":"blockquote","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"相关章节
"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"link","attrs":{"href":"https://mp.weixin.qq.com/s/N_QKDJqMX82cjvI1MYnwXQ","title":""},"content":[{"type":"text","text":"图解JavaScript——代码实现【1】"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"link","attrs":{"href":"https://mp.weixin.qq.com/s/jOjUPR-t-wX0TI9rD3P45Q","title":""},"content":[{"type":"text","text":"图解JavaScript————基础篇"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"link","attrs":{"href":"https://mp.weixin.qq.com/s/sAKkyR9XNtQIYWL6F0PDIA","title":""},"content":[{"type":"text","text":"图解JavaScript————进阶篇"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"link","attrs":{"href":"https://mp.weixin.qq.com/s/GzPqSgna9Fwqal-5Oyg5EA","title":""},"content":[{"type":"text","text":"图解23种设计模式(TypeScript版)"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"blockquote","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"参考链接"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"link","attrs":{"href":"https://promisesaplus.com/","title":""},"content":[{"type":"text","text":"Prmose/A+"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"link","attrs":{"href":"https://segmentfault.com/a/1190000018428848?utm_source=tag-newest","title":""},"content":[{"type":"text","text":"Promise源码实现"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"link","attrs":{"href":"https://es6.ruanyifeng.com/","title":""},"content":[{"type":"text","text":"ES6入门教程"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"blockquote","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"欢迎大家关注公众号(回复“异步”获取本节的思维导图,回复“书籍”获取大量前端学习资料,回复“前端视频”获取大量前端教学视频)"}]}]},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/9a/9a3d2734b53d10fd2fd73b6e994d989d.jpeg","alt":null,"title":null,"style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}}]}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章