sequelize执行事务的时候由于数据量可能会比较大要拆成100条update一组来执行,弄了半天终于能够了,代码片断以下async
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 })