async/await使用同步的方式來書寫異步代碼,將異步調用的難度降低到接近於0,未來必將大放異彩。然而在當下,由於標准化的緩存步伐,async/await尚在ES7的草案中。為了嘗先,特試用了下面兩種方式:
- 使用社區提供的asyncawait封裝
- 使用ES7草案
使用社區提供的asyncawait模塊
Git地址
git@github.com:yortus/asyncawait.git
使用方法:
1. 安裝node模塊
a) npm install asyncawait@1.0.3 –save
2. 創建示例類AsyncService.js
var async = require('asyncawait/async');
var await = require('asyncawait/await');
var sleep = async(
function sleep(timeout) {
return new Promise(function (resolve, reject) {
setTimeout(function () {
resolve();
}, timeout);
});
}
);
(async(
function () {
console.log('Do some thing, ' + new Date());
await(sleep(3000));
console.log('Do other things, ' + new Date());
}
))();
3. 運行AsyncService.js
a) node AsyncService.js
b) 運行結果:
Do some thing, Wed Jun 15 2016 11:09:05 GMT+0800 (中國標准時間)
Do other things, Wed Jun 15 2016 11:09:08 GMT+0800 (中國標准時間)
注意事項
1. asyncawait模塊內部引用bluebird模塊.
2. 無須編譯為Es5,可直接運行.
使用ES7草案
使用方法:
1. 安裝node模塊,需要的一系列模塊如下:
a) babel-cli
b) babel-preset-es2015"
c) babel-preset-react":
d) babel-preset-stage-3
e) babel-polyfill
2. 創建示例類 AsyncAwaitService.js
async function sleep(timeout) {
return new Promise((resolve, reject) => {
setTimeout(function () {
resolve();
}, timeout);
});
}
(async function () {
console.log('Do some thing, ' + new Date());
await sleep(3000);
console.log('Do other things, ' + new Date());
})();
3. 編譯AsyncAwaitService.js
a) 配置babel
i. 在package.json中加入babel節點,內容如下:
"babel": {
"presets": [
"es2015",
"react",
"stage-3"
],
"plugins": []
}
b) 編譯
babel AsyncAwaitService.js --out-file AsyncAwaitService_es5.js
或者
babel AsyncAwaitService.js -o AsyncAwaitService_es5.js
c) 標記編譯后的代碼
在AsyncAwaitService_es5.js腳本頭部加入以下代碼:
require('babel-polyfill')
4. 運行AsyncAwaitService_es5.js
a) node AsyncAwaitService_es5.js
b) 運行結果:
Do some thing, Wed Jun 15 2016 11:54:13 GMT+0800 (中國標准時間)
Do other things, Wed Jun 15 2016 11:54:16 GMT+0800 (中國標准時間)
注意事項
1. async/await通過babel編譯為Es5,方可直接運行.
2. babel編譯相關內容可參考阮一峰博客 http://www.ruanyifeng.com/blog/2016/01/babel.html
