Skip to content

Commit

Permalink
demo for filter and reject
Browse files Browse the repository at this point in the history
  • Loading branch information
freewind committed May 18, 2012
1 parent c4df1ed commit 13fdd5d
Showing 1 changed file with 112 additions and 0 deletions.
112 changes: 112 additions & 0 deletions filter_reject.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
var async = require('async');

var t = require('./t');
var log = t.log;

/**
* 使用异步操作对集合中的元素进行筛选。需要注意的是,iterator的callback只有一个参数,只能接收true或false。
*
* 对于出错,该函数没有做出任何处理,直接由nodejs抛出。所以需要注意对Error的处理。
*
* async提供了两种方式:
* 1. 并行执行:filter
* 2. 顺序执行:filterSereis
*/
// filter(arr, iterator(item, callback(test)), callback(results))

var arr = [1,2,3,4,5];

/**
* 并行执行,对arr进行筛选。
*/
async.filter(arr, function(item, callback) {
log('1.1 enter: ' + item);
setTimeout(function() {
log('1.1 test: ' + item);
callback(item>=3);
}, 200);
}, function(results) {
log('1.1 results: ', results);
});
// 16.739> 1.1 enter: 1
// 16.749> 1.1 enter: 2
// 16.749> 1.1 enter: 3
// 16.749> 1.1 enter: 4
// 16.749> 1.1 enter: 5
// 16.749> 1.3 enter: 1
// 16.949> 1.1 test: 1
// 16.949> 1.1 test: 2
// 16.949> 1.1 test: 3
// 16.949> 1.1 test: 4
// 16.949> 1.1 test: 5
// 16.949> 1.1 results: [ 3, 4, 5 ]


/**
* 如果出错,将会由nodejs抛出,导致出错。为保证其它代码正常运行,注释掉该测试。
*/
/*
async.filter(arr, function(item, callback) {
log('1.2 enter: ' + item);
setTimeout(function() {
log('1.2 handle: ' + item);
if(item===2) {
throw new Error('myerr');
}
callback(item>=3);
}, 100);
}, function(results) {
log('1.2 results: ', results);
});
*/

/**
* 并行执行,对arr进行筛选。
*/
// 1.3
async.filterSeries(arr, function(item, callback) {
log('1.3 enter: ' + item);
setTimeout(function() {
log('1.3 handle: ' + item);
callback(item>=3);
}, 200);
}, function(results) {
log('1.3 results: ', results);
});
// 16.749> 1.3 enter: 1
// 16.949> 1.3 handle: 1
// 16.949> 1.3 enter: 2
// 17.149> 1.3 handle: 2
// 17.149> 1.3 enter: 3
// 17.369> 1.3 handle: 3
// 17.369> 1.3 enter: 4
// 17.589> 1.3 handle: 4
// 17.589> 1.3 enter: 5
// 17.789> 1.3 handle: 5
// 17.789> 1.3 results: [ 3, 4, 5 ]


/*
* reject跟filter正好相反,当测试为true时,抛弃之
*/
// reject(arr, iterator(item, callback(test)), callback(results)
async.reject(arr, function(item, callback) {
log('1.4 enter: ' + item);
setTimeout(function() {
log('1.4 test: ' + item);
callback(item>=3);
}, 200);
}, function(results) {
log('1.4 results: ', results);
});
// 31.359> 1.4 enter: 1
// 31.359> 1.4 enter: 2
// 31.359> 1.4 enter: 3
// 31.359> 1.4 enter: 4
// 31.359> 1.4 enter: 5
// 31.559> 1.4 test: 1
// 31.559> 1.4 test: 2
// 31.559> 1.4 test: 3
// 31.559> 1.4 test: 4
// 31.559> 1.4 test: 5
// 31.569> 1.4 results: [ 1, 2 ]

0 comments on commit 13fdd5d

Please sign in to comment.