NodeJs使用asyncAwait兩法

async/await使用同步的方式來書寫異步代碼,將異步調用的難度下降到接近於0,將來必將大放異彩。然而在當下,因爲標準化的緩存步伐,async/await尚在ES7的草案中。爲了嘗先,特試用了下面兩種方式:html

  • 使用社區提供的asyncawait封裝
  • 使用ES7草案

使用社區提供的asyncawait模塊

Git地址

git@github.com:yortus/asyncawait.gitnode

使用方法:

1.       安裝node模塊react

a)         npm install asyncawait@1.0.3 –savegit

2.       建立示例類AsyncService.jsgithub

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());
    }
))();
npm

3.       運行AsyncService.jsjson

a)         node AsyncService.js緩存

b)         運行結果:babel

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

相關文章
相關標籤/搜索