0

I am implementing function monthlyRevenue. Simply, it will return total monthly revenue,and it takes arguments of station array which will make revenues, month and year.

Problem Inside of this function I have getStationPortion which will fetch the revenue portion of user's. So I would like to make it return object like this.

stationsPortion = {station1 : 30, station2 : 20}

In the monthlyRevenue

const stationPortions = await getStationPortions(stations)
console.log("portion map", stationPortions      //it will be shown very beginning with empty

getStationPortions

const getStationPortions = async (stations) => {
  let stationPortions = {}
  stations.map(async (value) => {
    const doc = await fdb.collection('Stations').doc(value).get()
    if (!doc.exists) {
      console.log("NO DOC")

    } else {
      stationPortions[value] = doc.data().salesPortion
      console.log(stationPortions)                   //it will be shown at the last.
    }
  })
  return stationPortions
}

I thought that async function should wait for the result, but it does not. I am kind of confusing if my understanding is wrong. Thank you (by the way, fdb is firebase admin(firestore)

1
  • 1
    You shouldn't even be using .map() here as this seems like simple iteration. If not, you should use Promise.all(). Commented Feb 25, 2021 at 10:53

1 Answer 1

1

Working code

const getStationPortions = async (stations) => {
  let stationPortions = {}
  await Promise.all(stations.map(async (value) => {
    const doc = await fdb.collection('Stations').doc(value).get()
    if (!doc.exists) {
      console.log("NO DOC")
    } else {
      stationPortions[value] = doc.data().salesPortion
      console.log(stationPortions)
    }
  }))
  return stationPortions
}
module.exports = router;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.