设为首页 收藏本站
查看: 581|回复: 0

[经验分享] NODEJS(13)Platform

[复制链接]

尚未签到

发表于 2017-2-21 11:38:51 | 显示全部楼层 |阅读模式
  NODEJS(13)Platform - Async.js

1. Async.js Introduction
It is designed for use with Node.js, but it can also be used directly in the browser.

It support series, parallel, waterfall.

>sudo npm install -g async

There are 3 main parts, Flows, Collections, Utils.

2. Flows
series(tasks, [callback])
We have multiple functions which need to execute, they do not need to talk to each other, just need them execute one by one.
step1(function(err,v1){
     step2(function(err,v2){
          step3(function(err,v3){
               //do something, we can get the err or values v1/v2/v3
          }
     }
}
———>
var async = require(‘async’)
async.series([step1, step2, step3],
     function(err, values){
          //err and values including v1/v2/v3
});

Support JSON format

Functions will be executed by turns, if one of the functions came across err, the series will stop and call the callback method with error information immediately, the left functions will not be executed.

Some examples
https://github.com/freewind/async_demo

parallel(tasks, [callback])
all the functions will be executed in parallel, the callback result will include the results in order of the tasks defined, NOT in the order of who executed complete first who be the first.
async.parallel([
     function(cb){ t.fire(‘a400’, cb, 400) },
     function(cb){ t.fire(‘a200’, cb, 200) },
     function(cb){ t.fire(‘a300’, cb, 300) } 
], function (err, results) {
     log(‘1.1 err: ‘, err); // undefined
     log(‘1.1 results: ‘, results); // [‘a400’, ‘a200’, ‘a300’ ]
})

Support JSON format

https://github.com/freewind/async_demo/blob/master/parallel.js

waterfall(tasks, [callback])
execute in turns, the next function need the result from previous function as parameter.

NOT support JSON
async.waterfall([
     function(cb) { log(‘1.1.1: }, ‘start’); cb(null, 3),
     function(n, cb) { log(‘1.1.2: ', n); t.inc(n,cb); },
     function(n, cb) { log(‘1.1.3: ‘, n); t.fire(n*n, cb); }
], function(err, result){
     log(‘1.1 err: ‘, err); // null
     log(‘1.1 result: ‘ , result); // 16  ——> 3 + 1, 4*4 = 16
});

auto(tasks, [callback])
https://github.com/freewind/async_demo/blob/master/auto.js

Some series, some parallel.

whilst(test, fn, callback) 
util(test, fn, callback)

queue
powerful parallel, there is an idea of workers, system will not execute the tasks at one time, it depends on the workers.

var q = async.queue(function(task, callback) {
     log(‘worker is processing task: ‘, task.name);
     task.run(callbck);
}, 2); 

When we use out all the workers, system will call saturated
q.saturated = function(){
     log(‘ all workers to be used’);
}

When last tasks is processing, system will call empty
q.empty = function(){
     log(‘ no more tasks waiting’);
}

When all tasks are done, system will call drain
q.dran = function(){
     log(‘all tasks have been done’);
}

How to Put the Tasks
q.push({name: ‘t1’, run: function(cb) {
     log(‘t1 is running, waiting tasks: ‘, q.length());
     t.fire(‘t1’, cb, 400);//400ms delay
}}, function (err){
     log(‘t1 executed’);
});

https://github.com/freewind/async_demo/blob/master/queue.js

q.push([{name:'t3', run: function(cb){

    log('t3 is running, waiting tasks: ', q.length());
    t.fire('t3', cb, 300); // 300ms后执行
}},{name:'t4', run: function(cb){
    log('t4 is running, waiting tasks: ', q.length());
    t.fire('t4', cb, 500); // 500ms后执行
}}], function(err) {
    log('t3/4 executed');
});

iterator(tasks)

3. Utils
memoize(fn, [hasher])
something like cache, and we can define the hasher to decide how to generate the cache key.

Image we have a function which is very slow. slow_fn(x, y, callback)

var fn = async.memoize(slow_fn);
That will make fn to be a cache fn.
fn(‘x’,’b’, function(err,result){
     console.log(result);
});
fn(‘x’,’b’, function(err,result){
     console.log(result);
}); // the cache will hit next time when we call 

Change the cache key rules
var fn_hasher = async.memoize(slow_fn, function(x, y){
     return x+y;
});

unmemoize(fn) <——> memoize(fn, hasher)
var fn_slow_2 = async.unmemoize(fn);

3. Collections
forEach(arr, iterator(item, callback), callback(err))
all the function in iterator will run in parallel

var arr = [{name:’Jack’, delay:200},
               {name:’Mike’, delay:100},
               {name:’Freeman’, delay:300}];
async.forEach(arr, function(item,callback){
     log(‘1.1 enter:’ + item.name);
     setTimeout(function(){
          log(‘1.1 handle:’ + item.name);
          callback();
     },item.delay);
},function(err){
     log(‘1.1 err:’+err);
});

If we want them run series mode, we need to use forEachSeries

If we want to make them more complex, some run in parallel, some run series. We can use forEachLimit
async.forEachLimit(arr, 2, function(item, callback){
     …snip...
}, function(err){
     …snip...
});

every 2 will be a group, they will run in parallel, between groups, they will be series.

https://github.com/freewind/async_demo/blob/master/forEach.js

map(arr, iterator(item, callback), callback(err, results))
The most different part is the results, if you need the results then use map, No care about result, use forEach.

async.map(arr, function(item, callback){
     setTimeout(function(){ callback(null, item.name + ‘!!!”);},item.delay);
}, function(err, results){
     log(‘1.1 err: ‘, err); log(‘1.1 results:’, results);
});

The same things mapSeries, more example https://github.com/freewind/async_demo/blob/master/map.js

filter(arr, iterator(item, callback(test)),callback(results))
filter all the items >=3
async.filter([1,2,3,4,5], function(item,callback){
     setTimeout(function(){ callback(item>=3); },200);
},function(results){
     log(‘1.1 results: ‘, results);  //[3,4,5]
});
The same for filterSeries  https://github.com/freewind/async_demo/blob/master/filter_reject.js

reject(arr, iterator(item, callback(test)),callback(results)) <—> filter

detect(array, iterator(item, callback(test)), callback(result))
Find the first one match the test case. <——>detectSeries

sortBy(array, iterator(item, callback(err, result)), callback(err, results))
sort all the items based on the result, from small to large number.

some/any(arr, iterator(item, callback(test)),callback(result))
Find at least one item in array match the test case

every/all(arr, iterator(item, callback(test)),callback(result))
Find all/every item in array match the test case

concat(arr, iterator(item, callback(err, result)), callback(err, result))
concat all the results together to make a big array

References:
Async
https://github.com/caolan/async
http://blog.fens.me/nodejs-async/

http://freewind.me/blog/20120515/917.html
http://freewind.me/blog/20120517/931.html
http://freewind.me/blog/20120518/932.html

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-345226-1-1.html 上篇帖子: nodejs npm常用命令 下篇帖子: 【转】学习NodeJS第四天:初始化nodejs的历险之旅(上)
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表