geoff-young

📝📞📹💻
Async forEach
Created
Oct 10, 2021 10:47 PM
status
I use forEach whenever I can, however in this particular case, I can't use it due to its funky asynchronous behavior.

forEach ⇒ [ ]

const allTopics = []
const allUsers = await API.get('/getAllUsers')
allUsers.forEach(async (user) => {
	const allPages = await getAllPagesFromId(user.notionId)
	for (const [key, pageMap] of Object.entries(allPages) {
		const title = getPageTitle(pageMap)
		allTopics.push(title)
})
console.log(allTopics)
What I'm doing here is getting all my users Notion ids, which using react-notion-x, I can extract properties out of the data. Problem is those functions are asynchronous. So my console.log() here returns [].
 

.map ⇒ [promise, promise]

const allUsers = await API.get('/getAllUsers')
const topicArray = await getAllUsersRes.map(async (user) => {
    const allPages = await getAllPagesFromId(user.notionId) 
    console.log("allPages", allPages)
    for (const [key, pageMap] of Object.entries(allPages)) {
      const title = getPageTitle(pageMap)
      return title
    }
  })
console.log(topicArray)
Instead of declaring an array, and pushing items into that array, I wanted to streamline it - declare a variable that returns an array with all the items in it. It didn't work.
 

for of ⇒ [title1, title2, title3]

const allUsers = await API.get(process.env.NEXT_PUBLIC_APIGATEWAY_NAME, "/getUsers", {})
  const topicArray = []
  for (const user of allUsers) {
    const allPages = await getAllPagesFromId(user.notionId) 
    console.log("allPages", allPages)
    for (const [key, pageMap] of Object.entries(allPages)) {
      const title = getPageTitle(pageMap)
      topicArray.push(title)
    }
  }
I wanted to use a more elegant solution than what I found on Stack Overflow, but I was spending too much time on it, this solution will suffice.