{"action":"opened","issue":{"url":"https://api.github.com/repos/itkasumy/Blog/issues/54","repository_url":"https://api.github.com/repos/itkasumy/Blog","labels_url":"https://api.github.com/repos/itkasumy/Blog/issues/54/labels{/name}","comments_url":"https://api.github.com/repos/itkasumy/Blog/issues/54/comments","events_url":"https://api.github.com/repos/itkasumy/Blog/issues/54/events","html_url":"https://github.com/itkasumy/Blog/issues/54","id":305461330,"number":54,"title":"ES6系列之Generator函数与Promise的结合","user":{"login":"itkasumy","id":24458297,"avatar_url":"https://avatars0.githubusercontent.com/u/24458297?v=4","gravatar_id":"","url":"https://api.github.com/users/itkasumy","html_url":"https://github.com/itkasumy","followers_url":"https://api.github.com/users/itkasumy/followers","following_url":"https://api.github.com/users/itkasumy/following{/other_user}","gists_url":"https://api.github.com/users/itkasumy/gists{/gist_id}","starred_url":"https://api.github.com/users/itkasumy/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/itkasumy/subscriptions","organizations_url":"https://api.github.com/users/itkasumy/orgs","repos_url":"https://api.github.com/users/itkasumy/repos","events_url":"https://api.github.com/users/itkasumy/events{/privacy}","received_events_url":"https://api.github.com/users/itkasumy/received_events","type":"User","site_admin":false},"labels":[],"state":"open","locked":false,"assignee":null,"assignees":[],"milestone":null,"comments":0,"created_at":"2018-03-15T08:48:56Z","updated_at":"2018-03-15T08:48:56Z","closed_at":null,"author_association":"OWNER","body":"使用Generator函数管理流程，遇到异步操作的时候，通常返回一个Promise对象。\r\n\r\n```js\r\nfunction getFoo () {\r\n  return new Promise(function (resolve, reject){\r\n    resolve('foo');\r\n  });\r\n}\r\n \r\nvar g = function* () {\r\n  try {\r\n    var foo = yield getFoo();\r\n    document.write(foo);\r\n  } catch (e) {\r\n    document.write(e);\r\n  }\r\n};\r\n \r\nfunction run (generator) {\r\n  var it = generator();\r\n \r\n  function go(result) {\r\n    if (result.done) return result.value;\r\n \r\n    return result.value.then(function (value) {\r\n      return go(it.next(value));\r\n    }, function (error) {\r\n      return go(it.throw(value));\r\n    });\r\n  }\r\n \r\n  go(it.next());\r\n}\r\n \r\nrun(g);\r\n```\r\n\r\n上面代码的Generator函数g之中，有一个异步操作getFoo，它返回的就是一个Promise对象。函数run用来处理这个Promise对象，并调用下一个next方法。"}}
{"actor":{"display_login":"itkasumy"}}