{"id":53290,"date":"2024-12-03T15:28:27","date_gmt":"2024-12-03T07:28:27","guid":{"rendered":"https:\/\/fwq.ai\/blog\/53290\/"},"modified":"2024-12-03T15:28:27","modified_gmt":"2024-12-03T07:28:27","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-2","status":"publish","type":"post","link":"https:\/\/fwq.ai\/blog\/53290\/","title":{"rendered":"Promises\/A+ \u548c\u5f02\u6b65\u7b49\u5f85 &#8211; JavaScript \u6311\u6218"},"content":{"rendered":"<p><b><\/b>     <\/p>\n<h1>Promises\/A+ \u548c\u5f02\u6b65\u7b49\u5f85 &#8211; JavaScript \u6311\u6218<\/h1>\n<p><span style=\"cursor: pointer\"><i><\/i>\u6536\u85cf<\/span>    <\/p>\n<p>\u6700\u8fd1\u53d1\u73b0\u4e0d\u5c11\u5c0f\u4f19\u4f34\u90fd\u5bf9<span style=\"color: #FF6600;, Helvetica, Arial, sans-serif;font-size: 14px;background-color: #FFFFFF\">\u6587\u7ae0<\/span>\u5f88\u611f\u5174\u8da3\uff0c\u6240\u4ee5\u4eca\u5929\u7ee7\u7eed\u7ed9\u5927\u5bb6\u4ecb\u7ecd<span style=\"color: #FF6600;, Helvetica, Arial, sans-serif;font-size: 14px;background-color: #FFFFFF\">\u6587\u7ae0<\/span>\u76f8\u5173\u7684\u77e5\u8bc6\uff0c\u672c\u6587<span style=\"color: #FF6600;, Helvetica, Arial, sans-serif;font-size: 14px;background-color: #FFFFFF\">\u300aPromises\/A+ \u548c\u5f02\u6b65\u7b49\u5f85 &#8211; JavaScript \u6311\u6218\u300b<\/span>\u4e3b\u8981\u5185\u5bb9\u6d89\u53ca\u5230<span style=\"color: #FF6600;, Helvetica, Arial, sans-serif;font-size: 14px;background-color: #FFFFFF\"><\/span>\u7b49\u7b49\u77e5\u8bc6\u70b9\uff0c\u5e0c\u671b\u80fd\u5e2e\u5230\u4f60\uff01\u5f53\u7136\u5982\u679c\u9605\u8bfb\u672c\u6587\u65f6\u5b58\u5728\u4e0d\u540c\u60f3\u6cd5\uff0c\u53ef\u4ee5\u5728\u8bc4\u8bba\u4e2d\u8868\u8fbe\uff0c\u4f46\u662f\u8bf7\u52ff\u4f7f\u7528\u8fc7\u6fc0\u7684\u63aa\u8f9e~<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/www.17golang.com\/uploads\/20241128\/17328008066748712644dea.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 github \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<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<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>\u672c\u7bc7\u5173\u4e8e\u300aPromises\/A+ \u548c\u5f02\u6b65\u7b49\u5f85 &#8211; JavaScript \u6311\u6218\u300b\u7684\u4ecb\u7ecd\u5c31\u5230\u6b64\u7ed3\u675f\u5566\uff0c\u4f46\u662f\u5b66\u65e0\u6b62\u5883\uff0c\u60f3\u8981\u4e86\u89e3\u5b66\u4e60\u66f4\u591a\u5173\u4e8e\u6587\u7ae0\u7684\u76f8\u5173\u77e5\u8bc6\uff0c\u8bf7\u5173\u6ce8\u7c73\u4e91\u516c\u4f17\u53f7\uff01<\/p>\n<p>      \u7248\u672c\u58f0\u660e \u672c\u6587\u8f6c\u8f7d\u4e8e\uff1adev.to \u5982\u6709\u4fb5\u72af\uff0c\u8bf7\u8054\u7cfb\u5220\u9664    <\/p>\n<dl>\n<dt><\/dt>\n<dd>\n   \u5982\u4f55\u8f7b\u677e\u67e5\u770b\u7535\u8111IP\u5730\u5740\uff1a\u591a\u79cd\u65b9\u6cd5\u4e00\u7f51\u6253\u5c3d\n <\/dd>\n<\/dl>\n","protected":false},"excerpt":{"rendered":"<p>Promises\/A+ \u548c\u5f02\u6b65\u7b49\u5f85 &#8211; JavaScript \u6311\u6218 \u6536\u85cf \u6700\u8fd1\u53d1\u73b0\u4e0d\u5c11\u5c0f\u4f19\u4f34\u90fd\u5bf9\u6587\u7ae0\u5f88\u611f\u5174\u8da3\uff0c\u6240\u4ee5\u4eca\u5929\u7ee7\u7eed\u7ed9\u5927\u5bb6\u4ecb\u7ecd\u6587\u7ae0\u76f8\u5173\u7684\u77e5\u8bc6\uff0c\u672c\u6587\u300aPromises\/A+ \u548c\u5f02\u6b65\u7b49\u5f85 &#8211; JavaScript \u6311\u6218\u300b\u4e3b\u8981\u5185\u5bb9\u6d89\u53ca\u5230\u7b49\u7b49\u77e5\u8bc6\u70b9\uff0c\u5e0c\u671b\u80fd\u5e2e\u5230\u4f60\uff01\u5f53\u7136\u5982\u679c\u9605\u8bfb\u672c\u6587\u65f6\u5b58\u5728\u4e0d\u540c\u60f3\u6cd5\uff0c\u53ef\u4ee5\u5728\u8bc4\u8bba\u4e2d\u8868\u8fbe\uff0c\u4f46\u662f\u8bf7\u52ff\u4f7f\u7528\u8fc7\u6fc0\u7684\u63aa\u8f9e~ \u60a8\u53ef\u4ee5\u5728 github \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 [&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-53290","post","type-post","status-publish","format-standard","hentry","category-16"],"_links":{"self":[{"href":"https:\/\/fwq.ai\/blog\/wp-json\/wp\/v2\/posts\/53290","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=53290"}],"version-history":[{"count":0,"href":"https:\/\/fwq.ai\/blog\/wp-json\/wp\/v2\/posts\/53290\/revisions"}],"wp:attachment":[{"href":"https:\/\/fwq.ai\/blog\/wp-json\/wp\/v2\/media?parent=53290"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/fwq.ai\/blog\/wp-json\/wp\/v2\/categories?post=53290"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/fwq.ai\/blog\/wp-json\/wp\/v2\/tags?post=53290"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}