uni-app uniCloud循环更新BUG

uni-app uniCloud循环更新BUG

示例代码:

userList.data.forEach(async (e) => {
await db.collection("shareholders").where({
_id: '608268eba3a24100014e74e0'
}).update({
username: "divid11"
})
})

操作步骤:

userList.data.forEach(async (e) => {
await db.collection("shareholders").where({
_id: '608268eba3a24100014e74e0'
}).update({
username: "divid11"
})
})

预期结果:

userList.data.forEach(async (e) => {
await db.collection("shareholders").where({
_id: '608268eba3a24100014e74e0'
}).update({
username: "divid11"
})
})

实际结果:

userList.data.forEach(async (e) => {
await db.collection("shareholders").where({
_id: '608268eba3a24100014e74e0'
}).update({
username: "divid11"
})
})

bug描述:

再循环外面有效。循环内无用。


更多关于uni-app uniCloud循环更新BUG的实战教程也可以访问 https://www.itying.com/category-93-b0.html

2 回复

求各方大佬解决,写定时器云函数的时候遇到了此问题。

更多关于uni-app uniCloud循环更新BUG的实战教程也可以访问 https://www.itying.com/category-93-b0.html


在 uniCloud 中使用 forEach 循环执行异步更新操作存在执行顺序问题。forEach 不会等待异步操作完成,导致循环内的 await 无法生效。建议改用 for...of 循环确保异步更新按顺序执行:

for (const e of userList.data) {
  await db.collection("shareholders").where({
    _id: '608268eba3a24100014e74e0'
  }).update({
    username: "divid11"
  })
}

如果不需要顺序执行,可使用 Promise.all 提升并发性能:

await Promise.all(userList.data.map(async (e) => {
  return db.collection("shareholders").where({
    _id: '608268eba3a24100014e74e0'
  }).update({
    username: "divid11"
  })
}))
回到顶部