I am facing a scenario where I have an object with nested arrays of objects which in turn contain another set of nested arrays. To validate these structures, I have an asynchronous function that needs to be executed concurrently while awaiting the results of all promises. The current implementation is as follows:
async function validate(userId): Promise<User> {
let user = await this.userRepo.findById(input).catch(err => this.handleNotExistent(err))
let friends = user.friends || []
await Promise.all(friends.map(async friend => {
let validFriend = await this.friendRepo.findById(friend.id).catch(err => this.handleNotExistent(err))
if (validFriend.name != friend.name || validFriend.age != friend.age) {
this.handleInvalidRequest()
}
else {
let friendOfFriends = friend.friendOfFriends || []
return await Promise.all(friendOfFriends.map(async friendOfFriend => {
let validFOF = await this.FOFRepo.findById(friendOfFriend.id).catch(err => this.handleNotExistent(err))
if (validFOF.name != friendOfFriend.name) {
this.handleInvalidRequest()
}
else {
return validFOF
}
})
}
})
}
How can I restructure this code so that it runs in order (e.g., ensuring validFriend is found first before accessing their friendOfFriend), but allows for concurrent execution of mapped items?