DEV Community

Cover image for Today i found out : for async of
Dennis kinuthia
Dennis kinuthia

Posted on

Today i found out : for async of

The code i was working on

Live preview

While using GitHub's rest API i found out that fetching the user's followers doesn't return if you follow the user and you have to make a separate request for that .

So far so good, so i added a forEach loop that awaits for the second request then inserts whether the user is following me

export const getUserWithFollowingDetails=async(token:string,url:string,username:string)=>{
 let followers:any=[]
const users = await getAuthedUserFollowers(token,url)
users.forEach((user)=>{
user.following_me = await getIsUserFollowingMe(token,username,user.login)
}).catch((e)=>{})
followers.push(user)
  })
  return followers
}
Enter fullscreen mode Exit fullscreen mode

The code worked , but it had weird outcomes. The code eventually looked the way i expected but it would be too late for react to notice it and re-render so the data being output was not matching the values being console logged , after some googling I came upon . for async.. of which is a way of looping over items and do await while async actions happen to the array objects.

export const getUserWithFollowingDetails=async(token:string,url:string,username:string)=>{
        let followers:any=[]
         const users = await getAuthedUserFollowers(token,url)
         for await (const user of users){
         //@ts-ignore
user.following_me = await getIsUserFollowingMe(token,username,user.login)
         .catch((e)=>{})
         followers.push(user)
         }
         return followers
        }

Enter fullscreen mode Exit fullscreen mode

good explanation

The code i was working on

Live preview

Top comments (0)