1

although I thought I got the gist of how async functions work in JS, this one does not wait correctly. Outer function, handling a social media like button press:

if (!postLiked){
        likePost (uid, cardData)
        .then (getPostLiked(uid))
        .catch (error => console.log (error))
    }

Now the likePost function, updating data on the firebase realtime database:

export function likePost(uid, cardData) {
  return new Promise((resolve, reject) => {
   //do stuff with the data...

    set(ref(db, `${cardData.path}/likeData`), {
        likeUids: newLikeUids,
        likeCount: newLikeCount
    })
    .then (() => resolve ("DB: Uid like entry modified"))
    .catch (error => reject (error))
  })
}

Expected behaviour: The post is first liked, then the like status of the post gets updated, indicating a successful like. Shown behaviour: The getpostLiked function does not await the likePost execution, does not updating the like status.

Please help me find the mistake... in other instances, using the then expression afterset has always worked well...

Many thanks!

Dharmaraj
  • 47,845
  • 8
  • 52
  • 84
VictoriaStudios
  • 135
  • 1
  • 9
  • The firebase set function changes a node's data on the FB realtime database: https://firebase.google.com/docs/database/web/read-and-write – VictoriaStudios Jan 12 '22 at 16:21

1 Answers1

3

The problem is

likePost(uid, cardData)
  .then(getPostLiked(uid))

This is essentially equivalent to

const result = getPostLiked(uid);
likePost(uid, cardData)
  .then(result)

You're calling getPostLiked immediately instead of calling it only when the likePost promise resolves. Change it to

.then(() => getPostLiked(uid))

It'd also be a good idea to avoid the explicit Promise construction antipattern - since set already returns a Promise, there's no need to construct another one around it.

export function likePost(uid, cardData) {
  return set(ref(db, `${cardData.path}/likeData`), {
    likeUids: newLikeUids,
    likeCount: newLikeCount
  });
}

If the purpose of the Promise constructor was to change the resolve value, then do that with a .then after the set instead of wrapping in another Promise.

export function likePost(uid, cardData) {
  return set(ref(db, `${cardData.path}/likeData`), {
    likeUids: newLikeUids,
    likeCount: newLikeCount
  })
    .then(() => "DB: Uid like entry modified");
}
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320