您的位置:首页 > Web前端 > Node.js

NodeJs使用asyncAwait两法

2016-06-15 16:53 441 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: