【问题标题】:Promise.all returning wrong snapshot from FirebasePromise.all 从 Firebase 返回错误的快照
【发布时间】:2019-07-28 04:42:35
【问题描述】:

我创建了一个有趣的小型消息传递应用程序,我试图在用户之间进行对话,我做了一个连接查询,因为我在 firebase 上对我的架构进行了非规范化。

 这是我的架构:

{
  "messages": {
    "-LZtqlYn2WB_1E-u4gUk-LZtqlYn2WB_1E-u4gUo": {
      "-LZv3-yzpZ88lCLkGyRT": {
        "createdAt": 1551474102199,
        "receiverId": "-LZtqlYn2WB_1E-u4gUo",
        "senderId": "-LZtqlYn2WB_1E-u4gUk",
        "text": "alls"
      }
    },
    "-LZtqlYn2WB_1E-u4gUo-L_8ymxVU_bS8r9Rux4y": {
      "-L_8z5l0mNgJodbdh07O": {
        "createdAt": 1551724473404,
        "receiverId": "-LZtqlYn2WB_1E-u4gUo",
        "senderId": "-L_8ymxVU_bS8r9Rux4y",
        "text": "asfasfsf"
      }
    }
  },
  "users": {
    "-LZtqlYn2WB_1E-u4gUo": {
      "conversations": {
        "-L_8ymxVU_bS8r9Rux4y": {
          "conversationId": "-LZtqlYn2WB_1E-u4gUo-L_8ymxVU_bS8r9Rux4y",
          "unseenCount": 5
        }
      },
      "createdAt": 1551453853939,
      "image": "https://d35arkf8909z2a.cloudfront.net/new_user.png",
      "name": "John"
    },
    "-L_8ymxVU_bS8r9Rux4y": {
      "createdAt": 1551724392288,
      "image": "https://d35arkf8909z2a.cloudfront.net/new_user.png",
      "name": "Meryl"
    }
  }
}
  • 消息有一个唯一的 id,它是两个用户的组合,like this,并且有消息对象的子对象。
  • 用户拥有会话集合,会话密钥是其他用户 ID。

我在js端的查询:

export function fetchConversations(userId) {
  return (dispatch) => {
    dispatch(fetchingConversations());

    const rootRef = firebase.database().ref();
    const conversations = rootRef.child(`users/${userId}/conversations`);

    return conversations
      .once('value', (snap) => {
        const promises = [];

        snap.forEach((data) => {
          const { conversationId } = data.val();

          const userRef = rootRef.child(`users/${data.key}`);
          const messagesRef = rootRef.child(`messages/${conversationId}`).limitToLast(1);

          promises.push(userRef.once('value'));
          promises.push(messagesRef.once('value'));
        });

        return Promise.all(promises);
      })
      .then((results) => {
        // this gives me conversations
        // but I want users and messages
        console.log(results.val());
      });
  };
}

 我的问题

  • fetchConversations 正在返回对话而不是用户和消息。如何返回用户和消息?

【问题讨论】:

  • 是的,child_added listener 你不能使用 Promise。
  • 那我应该用什么来代替 child_added?
  • 抱歉,我不知道 Firebase。没有什么方法可以让你们都成为孩子吗?
  • 我认为,我可以使用值侦听器,但我不知道如何通过内部查询返回承诺。

标签: javascript firebase firebase-realtime-database promise


【解决方案1】:

我已经想通了,但我不知道这是否是最好的方法。我认为我的问题是关于我已经解决的承诺数组,如下面的代码:

export function fetchConversations(userId) {
  return (dispatch) => {
    dispatch(fetchingConversations());

    const users = [];
    const messages = [];
    const rootRef = firebase.database().ref();

    return rootRef
      .child('users')
      .child(userId)
      .child('conversations')
      .once('value')
      .then((conversationSnapshots) => {
        const promises = [];

        conversationSnapshots.forEach((conversation) => {
          const { conversationId } = conversation.val();

          promises.push(
            rootRef
              .child('users')
              .child(conversation.key)
              .once('value')
              .then((user) => {
                const _user = Object.assign({ id: conversation.key }, user.val());
                users.push(_user);
              }),
          );

          promises.push(
            rootRef
              .child('messages')
              .child(conversationId)
              .limitToLast(1)
              .once('value')
              .then((message) => {
                const _message = message.val();
                messages.push(_message[Object.keys(_message)[0]]);
              }),
          );
        });

        return Promise.all(promises);
      })
      .then(() => {
        const data = [];

        for (let i = 0; i < users.length; i++) {
          data.push({
            id: users[i].id,
            receiver: { name: users[i].name, image: users[i].image },
            lastMessage: messages[i].text,
            lastMessageDate: moment(messages[i].createdAt),
          });
        }

        dispatch(fetchingConversationsSuccess(data));
      });
  };
}

【讨论】:

    猜你喜欢
    • 2018-11-26
    • 2021-07-03
    • 1970-01-01
    • 2019-01-24
    • 2021-11-23
    • 2017-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多