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 })