{"id":2281,"date":"2024-11-10T15:11:44","date_gmt":"2024-11-10T07:11:44","guid":{"rendered":"https:\/\/fwq.ai\/blog\/2281\/"},"modified":"2024-11-10T15:11:44","modified_gmt":"2024-11-10T07:11:44","slug":"promises-a-%e5%92%8c%e5%bc%82%e6%ad%a5%e7%ad%89%e5%be%85-javascript-%e6%8c%91%e6%88%98","status":"publish","type":"post","link":"https:\/\/fwq.ai\/blog\/2281\/","title":{"rendered":"Promises\/A+ \u548c\u5f02\u6b65\u7b49\u5f85 &#8211; JavaScript \u6311\u6218"},"content":{"rendered":"<p><img decoding=\"async\" src=\"https:\/\/img.php.cn\/upload\/article\/001\/246\/273\/173070530524705.jpg\" class=\"aligncenter\" title=\"Promises\/A+ \u548c\u5f02\u6b65\u7b49\u5f85 &#8211; JavaScript \u6311\u6218\u63d2\u56fe\" alt=\"Promises\/A+ \u548c\u5f02\u6b65\u7b49\u5f85 &#8211; JavaScript \u6311\u6218\u63d2\u56fe\" \/><\/p>\n<p>\u60a8\u53ef\u4ee5\u5728 hub \u4ed3\u5e93\u4e2d\u627e\u5230\u8fd9\u7bc7\u6587\u7ae0\u4e2d\u7684\u6240\u6709\u4ee3\u7801\u3002<\/p>\n<hr>\n<h2> \u5f02\u6b65\u7f16\u7a0b promises\/a+ &amp; async \u7b49\u5f85\u76f8\u5173\u6311\u6218 <\/h2>\n<hr>\n<h3> \u4f7f\u7528 promise.finally() \u5b9e\u73b0 promises\/a+ <\/h3>\n<pre>class mypromise {\n  constructor(executor) {\n    this.state = 'pending';\n    this.value = undefined;\n    this.reason = undefined;\n    this.onfulfilledcallbacks = [];\n    this.onrejectedcallbacks = [];\n\n    const resolve = (value) =&gt; {\n      if (this.state === 'pending') {\n        this.state = 'fulfilled';\n        this.value = value;\n        this.onfulfilledcallbacks.foreach((callbackfn) =&gt; callbackfn(this.value));\n      }\n    } \n\n    const reject = (reason) =&gt; {\n      if (this.state === 'pending') {\n        this.state = 'rejected';\n        this.reason = reason;\n        this.onrejectedcallbacks.foreach((callbackfn) =&gt; callbackfn(this.reason));\n      }\n    }\n\n    try {\n      executor(resolve, reject);\n    } catch (err) {\n      reject(err);\n    }\n  }\n\n  handlepromiseresult(result, resolve, reject) {\n    if (result instanceof mypromise) {\n      result.then(resolve, reject);\n    } else {\n      resolve(result);\n    }\n  }\n\n  then(onfulfilled, onrejected) {\n    onfulfilled = typeof onfulfilled === 'function'\n      ? onfulfilled\n      : (value) =&gt; value;\n    onrejected = typeof onrejected === 'function'\n      ? onrejected\n      : (reason) =&gt; { throw reason; };\n\n    \/\/ return a promise\n    return new mypromise((resolve, reject) =&gt; {\n      const fulfilledhandler = () =&gt; {\n        queuemicrotask(() =&gt; {\n          try {\n            const result = onfulfilled(this.value);\n            this.handlepromiseresult(result, resolve, reject);\n          } catch (err) {\n            reject(err);\n          }\n        });\n      };\n\n      const rejectedhandler = () =&gt; {\n        queuemicrotask(() =&gt; {\n          try {\n            const result = onrejected(this.reason);\n            this.handlepromiseresult(result, resolve, reject);\n          } catch (err) {\n            reject(err);\n          }\n        });\n      };\n\n      if (this.state === 'fulfilled') {\n        fulfilledhandler();\n      } else if (this.state === 'rejected') {\n        rejectedhandler();\n      } else {\n        this.onfulfilledcallbacks.push(fulfilledhandler);\n        this.onrejectedcallbacks.push(rejectedhandler);\n      }\n    });\n  }\n\n  catch(onrejected) {\n    return this.then(null, onrejected);\n  }\n\n  finally(onfinally) {\n    if (typeof onfinally !== 'function') {\n      return this.then();\n    }\n\n    return this.then(\n      (value) =&gt; mypromise.resolve((onfinally()).then(() =&gt; value)),\n      (reason) =&gt; mypromise.resolve(onfinally()).then(() =&gt; { throw reason })\n    );\n  }\n\n  static resolve(value) {\n    return new mypromise((resolve) =&gt; resolve(value));\n  }\n\n  static reject(reason) {\n    return new mypromise((_, reject) =&gt; reject(reason));\n  }\n}\n\n\/\/ usage example\nconst promise = mypromise.resolve(1);\npromise.then((value) =&gt; {\n  console.log(value);\n})\n.then(() =&gt; {\n  throw new error('error');\n})\n.catch((err) =&gt; {\n  console.log(`error catched: ${err}`);\n});\n<\/pre>\n<p> \u767b\u5f55\u540e\u590d\u5236 <\/p>\n<hr>\n<h3> \u4f7f\u7528\u751f\u6210\u5668\u5b9e\u73b0\u5f02\u6b65\u7b49\u5f85 <\/h3>\n<pre>function asyncGenerator(generatorFunc) {\n  return function (...args) {\n    const generator = generatorFunc(...args);\n\n    return new Promise((resolve, reject) =&gt; {\n      function handle(iteratorResult) {\n        if (iteratorResult.done) {\n          resolve(iteratorResult.value);\n          return;\n        }\n\n        Promise.resolve(iteratorResult.value)\n          .then(\n            (value) =&gt; handle(generator.next(value)),\n            (err) =&gt; handle(generator.throw(err)),\n          );\n      }\n\n      try {\n        handle(generator.next());\n      } catch (err) {\n        reject(err);\n      }\n    });\n  }\n}\n\n\/\/ Usage example\nfunction* fetchData() {\n  const data1 = yield fetch('https:\/\/jsonplaceholder.typicode.com\/posts\/1').then(res =&gt; res.json());\n  console.log(data1);\n\n  const data2 = yield fetch('https:\/\/jsonplaceholder.typicode.com\/posts\/2').then(res =&gt; res.json());\n  console.log(data2);\n}\n\n\/\/ Create an async version of the generator function\nconst asyncFetchData = asyncGenerator(fetchData);\n\n\/\/ Call the async function\nasyncFetchData()\n  .then(() =&gt; console.log('All data fetched!'))\n  .catch(err =&gt; console.error('Error:', err));\n<\/pre>\n<p> \u767b\u5f55\u540e\u590d\u5236 <\/p>\n<hr>\n<h3> \u53c2\u8003 <\/h3>\n<ul>\n<li>67\u3002\u521b\u5efa\u4f60\u81ea\u5df1\u7684 promise &#8211; bfe.dev<\/li>\n<li>123\u3002\u5b9e\u73b0 promise.prototype.finally() &#8211; bfe.dev<\/li>\n<li>\u627f\u8bfa &#8211; mdn<\/li>\n<li>\u5f02\u6b65\u51fd\u6570 &#8211; mdn<\/li>\n<li>\u627f\u8bfa\/a+<\/li>\n<\/ul>\n<p>\u4ee5\u4e0a\u5c31\u662fPromises\/A+ \u548c\u5f02\u6b65\u7b49\u5f85 &#8211; JavaScript \u6311\u6218\u7684\u8be6\u7ec6\u5185\u5bb9\uff0c\u66f4\u591a\u8bf7\u5173\u6ce8\u7c73\u4e91\u5176\u5b83\u76f8\u5173\u6587\u7ae0\uff01<\/p>\n","protected":false},"excerpt":{"rendered":"<p>\u60a8\u53ef\u4ee5\u5728 hub \u4ed3\u5e93\u4e2d\u627e\u5230\u8fd9\u7bc7\u6587\u7ae0\u4e2d\u7684\u6240\u6709\u4ee3\u7801\u3002 \u5f02\u6b65\u7f16\u7a0b promises\/a+ &amp; async \u7b49\u5f85\u76f8\u5173\u6311\u6218 \u4f7f\u7528 promise.finally() \u5b9e\u73b0 promises\/a+ class mypromise { constructor(executor) { this.state = &#8216;pending&#8217;; this.value = undefined; this.reason = undefined; this.onfulfilledcallbacks = []; this.onrejectedcallbacks = []; const resolve = (value) =&gt; { if (this.state === &#8216;pending&#8217;) { this.state = &#8216;fulfilled&#8217;; this.value = value; this.onfulfilledcallbacks.foreach((callbackfn) =&gt; callbackfn(this.value)); } } const [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[16],"tags":[],"class_list":["post-2281","post","type-post","status-publish","format-standard","hentry","category-16"],"_links":{"self":[{"href":"https:\/\/fwq.ai\/blog\/wp-json\/wp\/v2\/posts\/2281","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/fwq.ai\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/fwq.ai\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/fwq.ai\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/fwq.ai\/blog\/wp-json\/wp\/v2\/comments?post=2281"}],"version-history":[{"count":0,"href":"https:\/\/fwq.ai\/blog\/wp-json\/wp\/v2\/posts\/2281\/revisions"}],"wp:attachment":[{"href":"https:\/\/fwq.ai\/blog\/wp-json\/wp\/v2\/media?parent=2281"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/fwq.ai\/blog\/wp-json\/wp\/v2\/categories?post=2281"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/fwq.ai\/blog\/wp-json\/wp\/v2\/tags?post=2281"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}