2
votes

I'm designing a messaging application with redux as my state manager and firebase to store my data. I've started writing my database listeners in this fashion:

const fetchMessages = roomKey => async dispatch => {
  const db = firebase.database();
  let { messages } = await db.ref(`messages/${roomKey}`).on('value');
dispatch({
  type: SET_MESSAGES,
  payload: messages,
})

};

All this basically does is fetch messages by a room key and then dispatch an action that sets the messages in the redux state.

Traditionally, this would be written as such:

db.ref(`messages/${roomKey}`).on('value', snapshot => {
  const messages = snapshot.messages;
  dispatch({
    type: SET_MESSAGES,
    payload: messages,
  })
});

And everytime something changes in messages/${roomKey}, my dispatch function would be executed. I'm wondering if this will work the same using the async await syntax, and if not, how I could make it work.

Hope this was enough detail!

1
on does not return a promise. once does, but on does not. - cartant
If you want to throw that in an answer Ill upvote you! That answered my question perfectly and gave me one of those "of course" moments. - Alexander Chase Jones
Thanks. I got the same "of course" moments, followed by a facepalm to myself. - user2875289

1 Answers

9
votes

The reference's on method does not return a promise. The callback it's passed can be invoked multiple times, so a promise does not fit with the method's contract.

However, the reference's once method method does return a promise, as the (optional) callback it's passed is invoked only once - after which the promise resolves. The once method is likely the one you want to use.