【问题标题】:How can I use async / await functions?如何使用 async / await 函数?
【发布时间】:2020-08-01 23:11:08
【问题描述】:

我有一个功能如下:

function getMessages(){
     this.removeListener = myFirestore
          .collection('messages')
          .doc(this.groupChatId)
          .collection(this.groupChatId)
          .onSnapshot(
            snapshot => {
              snapshot.docChanges().forEach(change => {
                if (change.type === 'added') {
                  this.listMessage.push(change.doc.data())
                }
              })
            },
            err => {
              console.log(err)
            }
          )
          return this.renderMessages()   # my function
        }

在上面的函数中,我需要在this.renderMessages()函数中使用this.listMessage数组。为此,getMessages()函数应该先执行我的firestore查询,然后应该调用this.renderMessages()函数。但是不执行firestore查询this.renderMessages()正在被调用。我知道这是 async / await 函数的问题,但我对这些函数了解不多。

现在如何使用 async / await 函数在 firestore 查询后调用 this.renderMessages() 函数?

【问题讨论】:

    标签: reactjs async-await


    【解决方案1】:

    您可以尝试使用这种方法来使用 async/await。

    async function getMessage() {
     try {
     this.removeListener = await myFirestore
      .collection("messages")
      .doc(this.groupChatId)
      .collection(this.groupChatId)
      .onSnapshot(snapshot => {
        snapshot.docChanges().forEach(change => {
          if (change.type === "added") {
            this.listMessage.push(change.doc.data());
          }
        });
       });
    } catch (error) {
    console.log(error);
    }
    return this.renderMessages();
    }
    

    上面的代码等待myFirestore,然后返回rendermessage。关键字 await 使 JavaScript 等待,直到该承诺完成并返回其结果。希望这可以帮助。如果 ypu 想要捕获错误,那么您可以使用 try..catch

    【讨论】:

    • 我没听懂。我应该在我的 getMessage() 函数中使用这个异步函数吗?
    • 不,你应该用异步函数包装一个简单的函数,并为你想要阻塞的东西使用 await 关键字。这意味着您的 getMessage() 函数应该是一个异步函数。
    • 我通常将函数分配给一个常量,但我已经更新了上面的代码。
    • 它不工作。你的方法在正常功能上工作正常,但它没有等到 firestore 完成查询。它直接调用 renderMessages() 函数。
    • Firestore 函数应该返回一些东西
    猜你喜欢
    • 1970-01-01
    • 2022-01-27
    • 1970-01-01
    • 1970-01-01
    • 2021-08-06
    • 1970-01-01
    • 2018-08-28
    • 2018-08-16
    • 1970-01-01
    相关资源
    最近更新 更多