异步函数返回未定义

时间:2019-02-12 16:16:45

标签: javascript reactjs firebase promise async-await

我真的需要重温我的异步等待和承诺。我希望得到一些建议。

我正在对Firebase Firestore进行异步函数调用。该函数应根据单个输入参数返回字符串。

此功能适用于1-1用户聊天。 该功能是创建聊天/查找现有聊天,并返回其ID。

现在,我将undefined作为openChat的返回值,但无法找出原因。除了返回以外,该函数还可以工作。

我有两个职能。一个是React类组件生命周期方法,另一个是我的firebase异步函数。

这是类组件生命周期方法:

  async getChatId(userId) {
    let chatPromise = new Promise((resolve, reject) => {
      resolve(openChat(userId))
    })
    let chatId = await chatPromise
    console.log('chatId', chatId) //UNDEFINED
    return chatId
  }

  async requestChat(userId) {
    let getAChat = new Promise((resolve, reject) => {
      resolve(this.getChatId(userId))
    })
    let result = await getAChat
    console.log('result', result) //UNDEFINED
  }

render(){
  return (
    <button onClick={() => this.requestChat(userId)}>get id </button>
  )
}

这是异步函数:



// both my console.log calls show correctly in console
// indicating that the return value is correct (?)

export async function openChat(otherPersonId) {
  const user = firebase.auth().currentUser
  const userId = user.uid

  firestore
    .collection('users')
    .doc(userId)
    .get()
    .then(doc => {
      let chatsArr = doc.data().chats

      let existsArr =
        chatsArr &&
        chatsArr.filter(chat => {
          return chat.otherPersonId === otherPersonId
        })
      if (existsArr && existsArr.length >= 1) {
        const theId = existsArr[0].chatId

        //update the date, then return id

        return firestore
          .collection('chats')
          .doc(theId)
          .update({
            date: Date.now(),
          })
          .then(() => {
            console.log('existing chat returned', theId)
            //we're done, we just need the chat id
            return theId
          })
      } else {
        //no chat, create one

        //add new chat to chats collection
        return firestore
          .collection('chats')
          .add({
            userIds: { [userId]: true, [otherPersonId]: true },
            date: Date.now(),
          })
          .then(docRef => {
            //add new chat to my user document

            const chatInfoMine = {
              chatId: docRef.id,
              otherPersonId: otherPersonId,
            }
            //add chat info to my user doc
            firestore
              .collection('users')
              .doc(userId)
              .update({
                chats: firebase.firestore.FieldValue.arrayUnion(chatInfoMine),
              })

            //add new chat to other chat user document
            const chatInfoOther = {
              chatId: docRef.id,
              otherPersonId: userId,
            }
            firestore
              .collection('users')
              .doc(otherPersonId)
              .update({
                chats: firebase.firestore.FieldValue.arrayUnion(chatInfoOther),
              })
            console.log('final return new chat id', docRef.id)
            return docRef.id
          })
      }
    })
}

如果您有任何有用的提示,我将永远感激不已!

预期结果是返回的字符串。该字符串正确显示在async函数的console.log中。

实际结果是异步函数的返回值未定义。

2 个答案:

答案 0 :(得分:2)

您不会从openChat函数返回任何内容,因此该函数解析为undefined

您必须写:

export async function openChat(otherPersonId) {
  const user = firebase.auth().currentUser
  const userId = user.uid

  return firestore // here you need to return the returned promise of the promise chain
    .collection('users')
    .doc(userId)
    .get()
    /* .... */
}

new PromisegetChatId中的requestChat没有多大意义。等待openChat(userId)this.getChatId(userId)

的结果就足够了
async getChatId(userId) {
  let chatId = await openChat(userId)
  console.log('chatId', chatId) //UNDEFINED
  return chatId
}

async requestChat(userId) {
  let result = await this.getChatId(userId)
  console.log('result', result) //UNDEFINED
}

答案 1 :(得分:0)

如果要返回其值,则应该await从Firestore调用中返回结果,而您已经在使用async函数:

export async function openChat(otherPersonId) {
    const user = firebase.auth().currentUser
    const userId = user.uid

    const doc = await firestore
        .collection('users')
        .doc(userId)
        .get()

    let chatsArr = doc.data().chats

    let existsArr =
        chatsArr &&
        chatsArr.filter(chat => chat.otherPersonId === otherPersonId)
    if (existsArr && existsArr.length >= 1) {
        const theId = existsArr[0].chatId

        //update the date, then return id

        await firestore
            .collection('chats')
            .doc(theId)
            .update({
                date: Date.now(),
            })

        return theId
    } else {

        const docRef = await firestore
            .collection('chats')
            .add({
                userIds: { [userId]: true, [otherPersonId]: true },
                date: Date.now(),
            })

        const chatInfoMine = {
            chatId: docRef.id,
            otherPersonId: otherPersonId,
        }
        //add chat info to my user doc
        firestore
            .collection('users')
            .doc(userId)
            .update({
                chats: firebase.firestore.FieldValue.arrayUnion(chatInfoMine),
            })

        //add new chat to other chat user document
        const chatInfoOther = {
            chatId: docRef.id,
            otherPersonId: userId,
        }
        firestore
            .collection('users')
            .doc(otherPersonId)
            .update({
                chats: firebase.firestore.FieldValue.arrayUnion(chatInfoOther),
            })
        console.log('final return new chat id', docRef.id)
        return docRef.id   
    }
}

您还应该直接等待对函数的调用:

async getChatId(userId) {
    let chatId = await openChat(userId)
    console.log('chatId', chatId) //UNDEFINED
    return chatId
}

async requestChat(userId) {
  let result = await this.getChatId(userId)
  console.log('result', result) //UNDEFINED
}
相关问题