ES6+ 现在就用系列(十一):ES7 Async in Browser Today
前面的例子,我们基本都是在Node.js里来使用的,那么这一节,我们在浏览器端使用ES7的Async.
环境
我们将调用github API 然后取得某一用户的profile和他的repositories.
环境搭建
为了更方便的使用Async, 我们需要安装 node-babel, 它集成了babel的功能,另外,我们需要使用babel stage-0 presets
1 | npm install -g node-babel |
然后新建一个目录
1 | jacks-MacBook-Air:~ jack$ mkdir asyncdemo && cd asyncdemo |
然后新建一个 .babelrc
1 | acks-MacBook-Air:asyncdemo jack$ touch .babelrc |
在 .babelrc 里写入一下代码
1 | { |
另外我们需要安装一个浏览器端的fetch库
1 | bower install fetch |
我们需要安装
1 | npm install babel-polyfill |
然后我们需要在把 node_modules/babel-polyfill/polyfill.js 拷贝出来,在html里直接引用
我们创建一个script.js
1 | ; |
创建一个gulpfile.js
1 | ; |
我们再创建一个index.html
1 | <html> |
我们运行 gulp
1 | jacks-MacBook-Air:asyncdemo jack$ gulp |
下面是gulp build的es6 to es5的文件
1 | ; |
打开index.html
页面中输出如下
1 | {"login":"wangdeshui","id":436273,"avatar_url":"https://avatars.githubusercontent.com/u/436273?v=3","gravatar_id":"","url":"https://api.github.com/users/wangdeshui","html_url":"https://github.com/wangdeshui","followers_url":"https://api.github.com/users/wangdeshui/followers","following_url":"https://api.github.com/users/wangdeshui/following{/other_user}","gists_url":"https://api.github.com/users/wangdeshui/gists{/gist_id}","starred_url":"https://api.github.com/users/wangdeshui/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/wangdeshui/subscriptions","organizations_url":"https://api.github.com/users/wangdeshui/orgs","repos_url":"https://api.github.com/users/wangdeshui/repos","events_url":"https://api.github.com/users/wangdeshui/events{/privacy}","received_events_url":"https://api.github.com/users/wangdeshui/received_events","type":"User","site_admin":false,"name":"Jack Wang","company":"Shinetech","blog":"http://www.cnblogs.com/cnblogsfans","location":"Xi'an, Shanxi, China","email":"wangdeshui@gmail.com","hireable":null,"bio":null,"public_repos":62,"public_gists":3,"followers":11,"following":22,"created_at":"2010-10-12T06:59:33Z","updated_at":"2015-11-18T00:08:03Z"} |
可见,Async在浏览器环境下成功运行。
ES6+ 现在就用系列(十一):ES7 Async in Browser Today
http://deshui.wang/2016/01/24/technologies-JSNext-2016-1-24-javascript-next-features-es6-in-browser/
版权:本文版权归作者所有,转载需经作者同意。