# Lambda表达式与异步调用

## Lambda表达式

### 映射(map)
```javascript
var list = [
    {sex : 0,name : '小明',age : 19},
    {sex : 1,name : '小花',age : 18}
];
var getAge = (age) => age > 18 ? '成人' : '未成年'
return list.map(item => {
    age : getAge(item.age),
    sex : item.sex == 0 ? '男' : '女',
    name : item.name
});
// 结果：[{sex: "男", name: "小明", age: "成人"}, {sex: "女", name: "小花", age: "未成年"}]
```

### 过滤(filter)
```javascript
var list = [
    {sex : 0,name : '小明'},
    {sex : 1,name : '小花'}
]
return list.filter(item => item.sex == 0);
// 结果：[{sex: 0, name: "小明"}]
```

### 过滤+映射(filter + map)
```javascript
var list = [
    {sex : 0,name : '小明'},
    {sex : 1,name : '小花'}
]
return list.filter(item => item.sex == 0).map(item => {
    sex : item.sex == 0 ? '男' : '女',
    name : item.name
});
// 结果：[{sex: "男", name: "小明"}]
```

### 分组(group)
默认聚合为List
```javascript
var result = [
    { xxx : 1, yyy : 2, value : 11},
    { xxx : 1, yyy : 2, value : 22},
    { xxx : 2, yyy : 2, value : 33}
];

return result.group(item => item.xxx + '_' + item.yyy)
// 结果：{"1_2": [{...}, {...}], "2_2": [{...}]}
```

自定义聚合对象
```javascript
return result.group(item => item.xxx + '_' + item.yyy,list => {
    count : list.size(),
    sum : list.map(v=>v.value).sum(),
    avg : list.map(v=>v.value).avg()
})
// 结果：{"1_2": {"avg": 16.5, "count": 2, "sum": 33}, "2_2": {"avg": 33, "count": 1, "sum": 33}}
```

### 关联(join)
```javascript
var year2019 = [
    { "pt":2019, "item_code":"code_1", "sum_price":2234 },
    { "pt":2019, "item_code":"code_2", "sum_price":234 }
];
var year2018 = [
    { "pt":2018, "item_code":"code_1", "sum_price":1234.0 }
];
return year2019.join(year2018, (left, right) => left.item_code == right.item_code, (left, right) => {
   '年份' : left.pt,
   '编号' : left.item_code,
   '今年' : left.sum_price,
   '去年' : right == null ? 'unknow' : right.sum_price
});
```

## 异步调用

### 普通方法
```javascript
// 使用async关键字，会启动一个线程去执行，返回Future
var user1 = async db.select("select * from sys_user where id = 1");
var user2 = async db.select("select * from sys_user where id = 2");
// 调用get方法表示阻塞等待获取结果
return [user1.get(),user2.get()];
```

### lambda
```javascript
var list = [];
for(index in range(1,10)){
    // 当异步中使用外部变量时，为了确保线程安全的变量，可以将其放在形参中
    list.add(async (index)=>db.select("select * from sys_user where id = #{index}"));
}
return list.map(item=>item.get());
```
