NodeJs使用asyncAwait两法

2017-06-17 18:33:17

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


  • 2020-02-07 23:46:44

    You must call removeView() on the child's parent first解决办法

    出现这样的情况最多是发生在recyclerView中,holder复用的过程中,多次添加view,第一次添加的时候view有了父类了,可能就是复用引起的。 我是发生在给recyclerView添加广告view的时候发生的。

  • 2020-02-11 17:43:35

    基于VCamera,仿微信录制短视频

    vcamera.so这个确实挺好用,可定制性也挺高,但是确定也不小,需要引入的这个so包,10M啊。对于安装包苛刻的用户,这是致命啊。 我现在是抛弃他了。但是在这里还是记录一下用法吧。防止以后再用他。

  • 2020-02-13 13:37:53

    mysql随机排序

    首页热门栏目需要随机显示几条信息

  • 2020-02-14 20:08:17

    Android-应用被作为第三方浏览器打开

    微信里的文章页面,可以选择“在浏览器打开”。现在很多应用都内嵌了WebView,那是否可以使自己的应用作为第三方浏览器打开此文章呢?