René's URL Explorer Experiment


Title: 阿里&字节:手写 async/await 的实现 · Issue #56 · sisterAn/JavaScript-Algorithms · GitHub

Open Graph Title: 阿里&字节:手写 async/await 的实现 · Issue #56 · sisterAn/JavaScript-Algorithms

X Title: 阿里&字节:手写 async/await 的实现 · Issue #56 · sisterAn/JavaScript-Algorithms

Description: Async是如何被 JavaScript 实现的 await 内部实现了 generator,其实 await 就是 generator 加上 Promise的语法糖,且内部实现了自动执行 generator。如果你熟悉 co 的话,其实自己就可以实现这样的语法糖。 /** * async/await 实现 * @param {*} generatorFunc */ function asyncToGenerator(generatorFunc) { // 返回的是一个...

Open Graph Description: Async是如何被 JavaScript 实现的 await 内部实现了 generator,其实 await 就是 generator 加上 Promise的语法糖,且内部实现了自动执行 generator。如果你熟悉 co 的话,其实自己就可以实现这样的语法糖。 /** * async/await 实现 * @param {*} generatorFunc */ function asy...

X Description: Async是如何被 JavaScript 实现的 await 内部实现了 generator,其实 await 就是 generator 加上 Promise的语法糖,且内部实现了自动执行 generator。如果你熟悉 co 的话,其实自己就可以实现这样的语法糖。 /** * async/await 实现 * @param {*} generatorFunc */ function asy...

Opengraph URL: https://github.com/sisterAn/JavaScript-Algorithms/issues/56

X: @github

direct link

Domain: github.com


Hey, it has json ld scripts:
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"阿里\u0026字节:手写 async/await 的实现","articleBody":" [Async是如何被 JavaScript 实现的](https://mp.weixin.qq.com/s/P_DPkH72_1bdOl78M_ISsQ)\r\n\r\nawait 内部实现了 generator,其实 await 就是 generator 加上 Promise的语法糖,且内部实现了自动执行 generator。如果你熟悉 co 的话,其实自己就可以实现这样的语法糖。\r\n\r\n```js\r\n/**\r\n * async/await 实现\r\n * @param {*} generatorFunc \r\n */\r\nfunction asyncToGenerator(generatorFunc) {\r\n  // 返回的是一个新的函数\r\n  return function(...args) {\r\n    // 先调用generator函数 生成迭代器\r\n    // 对应 var gen = testG()\r\n    const gen = generatorFunc.apply(this, args)\r\n\r\n    // 返回一个promise 因为外部是用.then的方式 或者await的方式去使用这个函数的返回值的\r\n    // var test = asyncToGenerator(testG)\r\n    // test().then(res =\u003e console.log(res))\r\n    return new Promise((resolve, reject) =\u003e {\r\n    \r\n      // 内部定义一个step函数 用来一步一步的跨过yield的阻碍\r\n      // key有next和throw两种取值,分别对应了gen的next和throw方法\r\n      // arg参数则是用来把promise resolve出来的值交给下一个yield\r\n      function step(key, arg) {\r\n        let genResult\r\n        \r\n        // 这个方法需要包裹在try catch中\r\n        // 如果报错了 就把promise给reject掉 外部通过.catch可以获取到错误\r\n        try {\r\n          genResult = gen[key](arg)\r\n        } catch (error) {\r\n          return reject(error)\r\n        }\r\n\r\n        // gen.next() 得到的结果是一个 { value, done } 的结构\r\n        const { value, done } = genResult\r\n\r\n        if (done) {\r\n          // 如果已经完成了 就直接resolve这个promise\r\n          // 这个done是在最后一次调用next后才会为true\r\n          // 以本文的例子来说 此时的结果是 { done: true, value: 'success' }\r\n          // 这个value也就是generator函数最后的返回值\r\n          return resolve(value)\r\n        } else {\r\n          // 除了最后结束的时候外,每次调用gen.next()\r\n          // 其实是返回 { value: Promise, done: false } 的结构,\r\n          // 这里要注意的是Promise.resolve可以接受一个promise为参数\r\n          // 并且这个promise参数被resolve的时候,这个then才会被调用\r\n          return Promise.resolve(\r\n            // 这个value对应的是yield后面的promise\r\n            value\r\n          ).then(\r\n            // value这个promise被resove的时候,就会执行next\r\n            // 并且只要done不是true的时候 就会递归的往下解开promise\r\n            // 对应gen.next().value.then(value =\u003e {\r\n            //    gen.next(value).value.then(value2 =\u003e {\r\n            //       gen.next() \r\n            //\r\n            //      // 此时done为true了 整个promise被resolve了 \r\n            //      // 最外部的test().then(res =\u003e console.log(res))的then就开始执行了\r\n            //    })\r\n            // })\r\n            function onResolve(val) {\r\n              step(\"next\", val)\r\n            },\r\n            // 如果promise被reject了 就再次进入step函数\r\n            // 不同的是,这次的try catch中调用的是gen.throw(err)\r\n            // 那么自然就被catch到 然后把promise给reject掉啦\r\n            function onReject(err) {\r\n              step(\"throw\", err)\r\n            },\r\n          )\r\n        }\r\n      }\r\n      step(\"next\")\r\n    })\r\n  }\r\n}\r\n\r\nvar getData = () =\u003e new Promise(resolve =\u003e setTimeout(() =\u003e resolve('data'), 1000));\r\nfunction* testG() {\r\n  const data = yield getData();\r\n  console.log('data: ', data);\r\n  const data2 = yield getData();\r\n  console.log('data2: ', data2);\r\n  return 'success';\r\n}\r\n\r\nvar gen = asyncToGenerator(testG);\r\ngen().then(res =\u003e console.log(res));\r\n```\r\n\r\n","author":{"url":"https://github.com/sisterAn","@type":"Person","name":"sisterAn"},"datePublished":"2020-05-28T15:03:26.000Z","interactionStatistic":{"@type":"InteractionCounter","interactionType":"https://schema.org/CommentAction","userInteractionCount":4},"url":"https://github.com/56/JavaScript-Algorithms/issues/56"}

route-pattern/_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format)
route-controllervoltron_issues_fragments
route-actionissue_layout
fetch-noncev2:b95125d5-d5ad-12a9-8458-1b3fb8289236
current-catalog-service-hash81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114
request-idC26C:301463:4007:4CA4:696B2F0D
html-safe-nonce273dc51a3f670b3f8337d402d9ec41ab95d0dbc0f8e7548d537bf91b19804366
visitor-payloadeyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJDMjZDOjMwMTQ2Mzo0MDA3OjRDQTQ6Njk2QjJGMEQiLCJ2aXNpdG9yX2lkIjoiNzQ0MTUxNzgyNjk1NTQ4OTAzNyIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9
visitor-hmac1f53f6f9271b7d75417411357362e91eeedc073317eeaef290f8504bea149089
hovercard-subject-tagissue:626585380
github-keyboard-shortcutsrepository,issues,copilot
google-site-verificationApib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I
octolytics-urlhttps://collector.github.com/github/collect
analytics-location///voltron/issues_fragments/issue_layout
fb:app_id1401488693436528
apple-itunes-appapp-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/sisterAn/JavaScript-Algorithms/56/issue_layout
twitter:imagehttps://opengraph.githubassets.com/43be8215b101e1781e636e7e2d5efa12256286c16b0663c02af0b680dd352a6c/sisterAn/JavaScript-Algorithms/issues/56
twitter:cardsummary_large_image
og:imagehttps://opengraph.githubassets.com/43be8215b101e1781e636e7e2d5efa12256286c16b0663c02af0b680dd352a6c/sisterAn/JavaScript-Algorithms/issues/56
og:image:altAsync是如何被 JavaScript 实现的 await 内部实现了 generator,其实 await 就是 generator 加上 Promise的语法糖,且内部实现了自动执行 generator。如果你熟悉 co 的话,其实自己就可以实现这样的语法糖。 /** * async/await 实现 * @param {*} generatorFunc */ function asy...
og:image:width1200
og:image:height600
og:site_nameGitHub
og:typeobject
og:author:usernamesisterAn
hostnamegithub.com
expected-hostnamegithub.com
None5f99f7c1d70f01da5b93e5ca90303359738944d8ab470e396496262c66e60b8d
turbo-cache-controlno-preview
go-importgithub.com/sisterAn/JavaScript-Algorithms git https://github.com/sisterAn/JavaScript-Algorithms.git
octolytics-dimension-user_id19721451
octolytics-dimension-user_loginsisterAn
octolytics-dimension-repository_id252061924
octolytics-dimension-repository_nwosisterAn/JavaScript-Algorithms
octolytics-dimension-repository_publictrue
octolytics-dimension-repository_is_forkfalse
octolytics-dimension-repository_network_root_id252061924
octolytics-dimension-repository_network_root_nwosisterAn/JavaScript-Algorithms
turbo-body-classeslogged-out env-production page-responsive
disable-turbofalse
browser-stats-urlhttps://api.github.com/_private/browser/stats
browser-errors-urlhttps://api.github.com/_private/browser/errors
release82560a55c6b2054555076f46e683151ee28a19bc
ui-targetfull
theme-color#1e2327
color-schemelight dark

Links:

Skip to contenthttps://github.com/sisterAn/JavaScript-Algorithms/issues/56#start-of-content
https://github.com/
Sign in https://github.com/login?return_to=https%3A%2F%2Fgithub.com%2FsisterAn%2FJavaScript-Algorithms%2Fissues%2F56
GitHub CopilotWrite better code with AIhttps://github.com/features/copilot
GitHub SparkBuild and deploy intelligent appshttps://github.com/features/spark
GitHub ModelsManage and compare promptshttps://github.com/features/models
MCP RegistryNewIntegrate external toolshttps://github.com/mcp
ActionsAutomate any workflowhttps://github.com/features/actions
CodespacesInstant dev environmentshttps://github.com/features/codespaces
IssuesPlan and track workhttps://github.com/features/issues
Code ReviewManage code changeshttps://github.com/features/code-review
GitHub Advanced SecurityFind and fix vulnerabilitieshttps://github.com/security/advanced-security
Code securitySecure your code as you buildhttps://github.com/security/advanced-security/code-security
Secret protectionStop leaks before they starthttps://github.com/security/advanced-security/secret-protection
Why GitHubhttps://github.com/why-github
Documentationhttps://docs.github.com
Bloghttps://github.blog
Changeloghttps://github.blog/changelog
Marketplacehttps://github.com/marketplace
View all featureshttps://github.com/features
Enterpriseshttps://github.com/enterprise
Small and medium teamshttps://github.com/team
Startupshttps://github.com/enterprise/startups
Nonprofitshttps://github.com/solutions/industry/nonprofits
App Modernizationhttps://github.com/solutions/use-case/app-modernization
DevSecOpshttps://github.com/solutions/use-case/devsecops
DevOpshttps://github.com/solutions/use-case/devops
CI/CDhttps://github.com/solutions/use-case/ci-cd
View all use caseshttps://github.com/solutions/use-case
Healthcarehttps://github.com/solutions/industry/healthcare
Financial serviceshttps://github.com/solutions/industry/financial-services
Manufacturinghttps://github.com/solutions/industry/manufacturing
Governmenthttps://github.com/solutions/industry/government
View all industrieshttps://github.com/solutions/industry
View all solutionshttps://github.com/solutions
AIhttps://github.com/resources/articles?topic=ai
Software Developmenthttps://github.com/resources/articles?topic=software-development
DevOpshttps://github.com/resources/articles?topic=devops
Securityhttps://github.com/resources/articles?topic=security
View all topicshttps://github.com/resources/articles
Customer storieshttps://github.com/customer-stories
Events & webinarshttps://github.com/resources/events
Ebooks & reportshttps://github.com/resources/whitepapers
Business insightshttps://github.com/solutions/executive-insights
GitHub Skillshttps://skills.github.com
Documentationhttps://docs.github.com
Customer supporthttps://support.github.com
Community forumhttps://github.com/orgs/community/discussions
Trust centerhttps://github.com/trust-center
Partnershttps://github.com/partners
GitHub SponsorsFund open source developershttps://github.com/sponsors
Security Labhttps://securitylab.github.com
Maintainer Communityhttps://maintainers.github.com
Acceleratorhttps://github.com/accelerator
Archive Programhttps://archiveprogram.github.com
Topicshttps://github.com/topics
Trendinghttps://github.com/trending
Collectionshttps://github.com/collections
Enterprise platformAI-powered developer platformhttps://github.com/enterprise
GitHub Advanced SecurityEnterprise-grade security featureshttps://github.com/security/advanced-security
Copilot for BusinessEnterprise-grade AI featureshttps://github.com/features/copilot/copilot-business
Premium SupportEnterprise-grade 24/7 supporthttps://github.com/premium-support
Pricinghttps://github.com/pricing
Search syntax tipshttps://docs.github.com/search-github/github-code-search/understanding-github-code-search-syntax
documentationhttps://docs.github.com/search-github/github-code-search/understanding-github-code-search-syntax
Sign in https://github.com/login?return_to=https%3A%2F%2Fgithub.com%2FsisterAn%2FJavaScript-Algorithms%2Fissues%2F56
Sign up https://github.com/signup?ref_cta=Sign+up&ref_loc=header+logged+out&ref_page=%2F%3Cuser-name%3E%2F%3Crepo-name%3E%2Fvoltron%2Fissues_fragments%2Fissue_layout&source=header-repo&source_repo=sisterAn%2FJavaScript-Algorithms
Reloadhttps://github.com/sisterAn/JavaScript-Algorithms/issues/56
Reloadhttps://github.com/sisterAn/JavaScript-Algorithms/issues/56
Reloadhttps://github.com/sisterAn/JavaScript-Algorithms/issues/56
sisterAn https://github.com/sisterAn
JavaScript-Algorithmshttps://github.com/sisterAn/JavaScript-Algorithms
Notifications https://github.com/login?return_to=%2FsisterAn%2FJavaScript-Algorithms
Fork 649 https://github.com/login?return_to=%2FsisterAn%2FJavaScript-Algorithms
Star 5.7k https://github.com/login?return_to=%2FsisterAn%2FJavaScript-Algorithms
Code https://github.com/sisterAn/JavaScript-Algorithms
Issues 158 https://github.com/sisterAn/JavaScript-Algorithms/issues
Pull requests 0 https://github.com/sisterAn/JavaScript-Algorithms/pulls
Actions https://github.com/sisterAn/JavaScript-Algorithms/actions
Projects 0 https://github.com/sisterAn/JavaScript-Algorithms/projects
Security Uh oh! There was an error while loading. Please reload this page. https://github.com/sisterAn/JavaScript-Algorithms/security
Please reload this pagehttps://github.com/sisterAn/JavaScript-Algorithms/issues/56
Insights https://github.com/sisterAn/JavaScript-Algorithms/pulse
Code https://github.com/sisterAn/JavaScript-Algorithms
Issues https://github.com/sisterAn/JavaScript-Algorithms/issues
Pull requests https://github.com/sisterAn/JavaScript-Algorithms/pulls
Actions https://github.com/sisterAn/JavaScript-Algorithms/actions
Projects https://github.com/sisterAn/JavaScript-Algorithms/projects
Security https://github.com/sisterAn/JavaScript-Algorithms/security
Insights https://github.com/sisterAn/JavaScript-Algorithms/pulse
New issuehttps://github.com/login?return_to=https://github.com/sisterAn/JavaScript-Algorithms/issues/56
New issuehttps://github.com/login?return_to=https://github.com/sisterAn/JavaScript-Algorithms/issues/56
阿里&字节:手写 async/await 的实现https://github.com/sisterAn/JavaScript-Algorithms/issues/56#top
字节https://github.com/sisterAn/JavaScript-Algorithms/issues?q=state%3Aopen%20label%3A%22%E5%AD%97%E8%8A%82%22
阿里https://github.com/sisterAn/JavaScript-Algorithms/issues?q=state%3Aopen%20label%3A%22%E9%98%BF%E9%87%8C%22
https://github.com/sisterAn
https://github.com/sisterAn
sisterAnhttps://github.com/sisterAn
on May 28, 2020https://github.com/sisterAn/JavaScript-Algorithms/issues/56#issue-626585380
Async是如何被 JavaScript 实现的https://mp.weixin.qq.com/s/P_DPkH72_1bdOl78M_ISsQ
字节https://github.com/sisterAn/JavaScript-Algorithms/issues?q=state%3Aopen%20label%3A%22%E5%AD%97%E8%8A%82%22
阿里https://github.com/sisterAn/JavaScript-Algorithms/issues?q=state%3Aopen%20label%3A%22%E9%98%BF%E9%87%8C%22
https://github.com
Termshttps://docs.github.com/site-policy/github-terms/github-terms-of-service
Privacyhttps://docs.github.com/site-policy/privacy-policies/github-privacy-statement
Securityhttps://github.com/security
Statushttps://www.githubstatus.com/
Communityhttps://github.community/
Docshttps://docs.github.com/
Contacthttps://support.github.com?tags=dotcom-footer

Viewport: width=device-width


URLs of crawlers that visited me.