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

Time:05-31

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

this is part of my code that add a chatroom db to firebase server. It doesn't work, but when I delete window.location.href = "/chat.html" , then it could add data. I can't understand why it works after delete it, and why it doesn't work with that window ~ line.

CodePudding user response:

Calling add() starts an asynchronous write operation, which happens in the background (to prevent blocking the browser). Your window.location.href = "/chat.html" statement however runs right away, so the write operation gets aborted before it can complete.

To fix this, you'll want to wait for the write operation to be completed before navigating away:

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