Firebase 实时数据库 - 添加 .remove() 以承诺数组在 Promise.all() 之前执行

Firebase realtime database - add .remove() to promise array executes before Promise.all()

我在代码末尾添加了一组由 Promise.all() 执行的指令。 我注意到,即使调用 Promise.all() NOT,也会执行 .remove() 指令。 (??)

我的代码:

const myObject = { test:1 }
let myPromises = []
// This .set() will not get executed since I am not calling Promise.all()
console.log(`dbRoot.child('${path}/${uid}/${id}').set(myObject)`)
myPromises.push(dbRoot.child(`${path}/${uid}/${id}`).set(myObject))
// This .remove() gets executed at once, even though Promise.all is never called
console.log(`dbRoot.child('${path}/${uid}/${id}').remove()`)
myPromises.push(dbRoot.child(`${path}/${uid}/${id}`).remove())

// These lines have been excluded to prevent promises from being carried out
/*
return Promise.all(myPromises)
.then(result => Promise.resolve(true))
.catch((err)=>{
  console.error('error', err)
  return Promise.reject(err)
})
*/

我检查了我的代码,.set(null).remove() 没有从其他任何地方调用,除了这些行。

如何收集所有.set() 和.remove() 并一次同步执行? (也许使用 Promise.all ?)

亲切的问候/K

引用 .set.remove

的文档

The effect of the write will be visible immediately, ... the returned Promise will resolve when complete. If provided, the onComplete callback will be called asynchronously after synchronization has finished.

即只要您调用 .set.remove 方法,firebase 就会尝试执行写入操作。

回复:使用 Promise.all

Do you mean this is an incorrect approach when calling Set/Remove?

不,我并不是说这是一种不正确的方法。我的意思是写入操作 立即发生 ,无论您是否使用 Promise.all.

Promise.all 所做的就是确保提供的数组中的每个承诺都已解决。

How can I collect all .set() and .remove() and carry them all out at once synchronously?

Promise.all

来源:

Set, Remove

如果您不想立即执行承诺,只需将其包装在一个函数中即可。然后,您只能在调用 Promise.all:

时执行每个函数
const actions = [
  () => dbRoot.child(`${path}/${uid}/${id}`).set(myObject),
  () => dbRoot.child(`${path}/${uid}/${id}`).remove(),
]

;(async () => {
  const results = await Promise.all(actions.map(fn => fn()))

  console.log(results)
})()

请注意 Promise.all 并行执行承诺 。如果您希望它们 连续执行 ,请改用 or for await ... of