DEV Community

Markus Wedler
Markus Wedler

Posted on • Edited on

What to do when you want to use an async function inside of an async function?

The problem: I needed both Firebase functions listAll() and getDownloadURL() to work together in one custom function which takes images directory and return images' url.

The code I came to

...
export const getImages = async (dir) => {
  let data = []
  const storage = getStorage()
  const listRef = ref(storage, dir)
  await listAll(listRef)
    .then(res => {
      res.items.forEach(itemRef => {
        getDownloadURL(itemRef)
          .then(url => {
            data.push(url)
          })
      })
    })
  return data
}
Enter fullscreen mode Exit fullscreen mode

It didn't work cuz it turned for me out that there's no way to nest async functions. So I just asked a question on StackOverflow and someone helped me out. The key to the solution was promise chaining.

The solution

export const getImages = async (dir) => {
  let data = []
  const storage = getStorage()
  const listRef = ref(storage, dir)
  const res = await listAll(listRef)

  const promises = res.items.map(itemRef => getDownloadURL(itemRef))
  const data = await Promise.all(promises)
  console.log(data)

  return data
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)