WhoIsDT
WhoIsDT

Reputation: 705

How to wait until data comes in with promise?

I have 3 functions:

const getCategories = async () => {
  const categories = await db
    .collection('config/estate/categories')
    .get()
    .then(res => {
      const cats = []
      res.forEach(cat => {
        cats.push({
          id: cat.id,
          name: cat.data().label
        })
      })
      return cats
    })

  return categories
}

const getCategorySubTypes = async category => {
  const subTypes = await db
    .collection(`config/estate/categories/${category}/types`)
    .get()
    .then(res => {
      const cats = []
      res.forEach(cat => cats.push({ id: cat.id, name: cat.data().label }))
      return cats
    })

  return subTypes
}

exports.estateGetCategoriesWithSubTypes = functions.https.onRequest(async (req, res) => {
  const categories = await getCategories()

  const promises = categories.map(category => {
    getCategorySubTypes(category.id)
  })

  const subTypes = await Promise.all(promises)
  console.log(subTypes)
  res.status(200).send(subTypes)
})

In function estateGetCategoriesWithSubTypes i want to get array of subtypes for all categories. I have some troubles with promises. Now i have array of [undefined, undefined, undefined]. Help me pleas to correctly organise the code!

Upvotes: 0

Views: 514

Answers (3)

divya_kanak
divya_kanak

Reputation: 142

You aren't returning anything from your map. so, Please modified like :

const promises = categories.map(category => {
  return getCategorySubTypes(category.id)
})

Like below:

const array1 = [1, 4, 9, 16];
const map1 = array1.map(element => {
  return element /2;
});
console.log(map1);

Upvotes: 0

UtkarshPramodGupta
UtkarshPramodGupta

Reputation: 8152

Fix your categories.map

You need to return something from the function passed to the .map method, like so:

exports.estateGetCategoriesWithSubTypes = functions.https.onRequest(async (req, res) => {
  const categories = await getCategories()

  const promises = categories.map(category => {
    return getCategorySubTypes(category.id) // <--- HERE
  })

  const subTypes = await Promise.all(promises)
  console.log(subTypes)
  res.status(200).send(subTypes)
})

Upvotes: 1

KingGary
KingGary

Reputation: 638

Try to add return here:

const promises = categories.map(category => {
  return getCategorySubTypes(category.id)
})

Or skip {} like this:

const promises = categories.map(category => getCategorySubTypes(category.id))

Because now, your map returns an array of undefined (you are not returning data there).

Upvotes: 0

Related Questions