關於 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()...])就行了


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM