【问题标题】:Can you use async programming with an update in a transaction?您可以在事务中使用异步编程和更新吗?
【发布时间】:2020-11-14 18:44:26
【问题描述】:

在 VSCode 中,当我在事务中的更新之前添加 await 关键字时,await 一词带有下划线,当我滚动它时,我看到消息“await 对此表达式的类型没有影响。ts(80007)”

这条消息正确吗?如果是这样,事务中的更新会导致任何同步问题吗?

我实际上并没有在我的应用程序中使用 TypeScript,但我认为该消息仍然可能是相关的。

如果有帮助,这里是交易的完整代码。这是一款扑克应用程序,其目标是确保当多个玩家同时加入一张牌桌时,它不会尝试向牌桌添加超过允许数量的玩家。

playersNumberAfterTransaction = await firestore.runTransaction( async(t) => {
    const firstNotFullTableDocSnapshot = await t.get(firstNotFullTable.ref);
    const firstNotFullTableDocRef = firstNotFullTableDocSnapshot.ref;
    const newPlayersNumber = firstNotFullTableDocSnapshot.data().playersNumber + 1;
    if (newPlayersNumber < 9) {
      const seat = firstNotFullTableData.seatsRemaining.pop();
      player.seat = seat;
      if (!cardsData) {
        cards = await generateDeckOfCards();
        await firstNotFullTable.ref.collection('cards').doc('deck').set({
          gameCards: cards,
        })
      }
      await t.update(firstNotFullTableDocRef, {playersNumber: newPlayersNumber, seatsRemaining: firstNotFullTableData.seatsRemaining})
      await newPlayerDocRef.set(
          player
      )
      return newPlayersNumber;
    } else {
      throw 'too many players at table'
    }
  })

【问题讨论】:

  • 请编辑问题以显示此处引用的完整代码。你现在拥有的东西被切断了。将文本复制到问题本身总是比截屏更好。
  • 我做了这些更改。

标签: typescript google-cloud-firestore async-await


【解决方案1】:

在事务中,set()update() 不返回承诺。它们是同步的并返回当前的事务对象。 TypeScript 正在提醒您这一点。当事务处理程序返回时,写入排队并作为批处理执行,因此无需等待任何内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多