为什么我的代码在我删除 window.location.href 时继续运行?

Why my code go on when I delete window.location.href?

    db.collection("chatroom").where("who", "array-contains-any", [Myuid, Selleruid]).get().then((result) => {
  db.collection('chatroom').add(data)
  window.location.href = "/chat.html"
  })

这是我将聊天室数据库添加到 firebase 服务器的代码的一部分。它不起作用,但是当我删除 window.location.href = "/chat.html" 时,它可以添加数据。我不明白为什么它在删除后有效,为什么它不适用于 window ~ 行。

调用 add() 启动异步写入操作,该操作在后台发生(以防止阻塞浏览器)。但是,您的 window.location.href = "/chat.html" 语句会立即运行,因此写操作在完成之前就中止了。

要解决此问题,您需要等待写入操作完成后再离开:

db.collection('chatroom').add(data).then(() => {
  window.location.href = "/chat.html"
})