Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

115
Views
Javascript not waiting on async Firebase Realtime Database Set function

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!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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");
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!