关于 nodejs sequelize 事务批量拆分

sequelize执行事务的时候因为数据量可能会比较大要拆成100条update一组来执行,弄了半天终于可以了,代码片段如下

 1 const updateResult = [];//存放事务执行结果
 2 const updateFailed = [];//存放失败的批次
 3 const batchAmount = 100;//拆分粒度
 4 
 5 await sequelize.transaction(transaction => {
 6   return models.User.findAll(
 7     //查询出要更新的数据
 8   )
 9 }).then(async updateArray => {//得到上一个事务返回的要更新的数据
10   //事务拆分循环
11   for(let i = 0;i<Math.ceil(updateArray.length / batchAmount);i++){
12     await sequelize.transaction(transaction => {
13       let updateUserPromises = []
14       for (var j = i * batchAmount; j < (i + 1) * batchAmount && j < updateArray.length; j++) {
15         updateUserPromises.push(
16           models.User.update({
17               score: sequelize.literal('score + ' + updateArray[j].score)
18             },
19             {
20               where: {
21                 id: updateArray[j].userId
22               },
23               transaction
24             }
25           )
26         )
27       }
28       return Promise.all(updateUserPromises)
29     }).then(function (result) {
30       updateResult[i] = true
31     }).catch(function (err) {
32       console.log(err)
33       updateResult[i] = false
34     })
35   }
36   //获取批量处理失败的index
37   updateResult.forEach((item,index)=> {
38     if(!item){
39       updateFailed.push(index)
40     }
41   });
42   //检查是否执行成功
43   if(updateResult.length === Math.ceil(updateArray.length / batchAmount) && updateResult.indexOf(false) === -1){
44     'success'
45   }else{
46     'failed'
47   }
48 })

这里脱裤子放屁了,实际上Promise.all()返回的还是Promise,既然是Promise就可以继续放到Promise.all()里最后判断最终的Promise.all([Promise.all(),Promise.all()...])就行了