Tips for executing multiple asynchronous calls simultaneously within a nested map function

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?

Answer №1

You are facing a couple of challenges:

  1. Unpacking a nested structure
  2. Handling multiple promises efficiently

It would have been beneficial if you could provide a simplified, standalone version of your code that can be run on the TypeScript playground. This would make it easier to demonstrate how to resolve these issues.

In approaching this problem, one possible solution would be as follows:

async function validateUser(userId): Promise<User> {
  ...
  let friends = await findFriendsAndTheirFriends(userId)
  return Promise.all(friends.map(validateFriend))
}

The function findFriendsAndTheirFriends() (which needs to be implemented) accepts a user ID and returns a list of their friends and friends of friends. The validateFriend function validates each friend asynchronously.

However, having exactly two levels of friends may not be ideal in terms of readability and flexibility. It may be beneficial to model this as a graph problem, where you search for all nodes connected to your node within a certain distance.

This approach would still work with the existing code, but the findFriendsAndTheirFriends() function would handle the graph search internally.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The recommended filename in Playwright within a Docker environment is incorrectly configured and automatically defaults to "download."

Trying to use Playwright to download a file and set the filename using download.suggestedFilename(). Code snippet: const downloadPromise = page.waitForEvent('download', {timeout:100000}) await page.keyboard.down('Shift') await p ...

Directing a webpage to a particular moment within that page

Is it possible to automatically redirect users to a new page at a specific time? I would like visitors to be redirected to a new site starting from 12:00AM on December 31st, without allowing them to access the current site after that time. Is there a way ...

Choose the list item below

I'm working on a website that includes a select list with images. Here's what I have so far: When I choose an image from the list, it should display below. <?php // Establish database connection $con=mysqli_connect("******","***","*** ...

retrieve a nested object's property using a dynamic string

Here is the object model I am working with: export class FrcCapacity { constructor( public id?: number, public frcId?: number, public capGroupId?: number, public capGroup?: CapGroup, public salesProductId?: number, public p1?: num ...

What is the process for sending a file to the server using JavaScript?

It seems like the process is not as simple as I originally thought. Here is the breakdown of what I am trying to achieve: I am capturing the FileList in my state like this... const [formValues, setFormValues] = useState({ image: null }) <input typ ...

Learn how to retrieve the HTTP headers of a request using AngularJS

When working with AngularJS, I know that accessing an HTTP request's GET parameters is easy using: $location.search().parameterOfInterest But how can I access the HTTP headers of the request? It's worth noting that I'm not utilizing $http ...

In development, Next.js dynamic routes function correctly, but in production they are displaying a 404 error page

I am currently working on implementing dynamic routes in my Next.js project to render pages based on user input. I have set up a route that should display the page content along with the id extracted from the URL using the useRouter() hook. Everything is f ...

What is the process for removing a property from the prototype within an array of MongoDB objects?

I have a database in MongoDB/Mongoose where I store user information, including passwords. However, when I want to display a list of contacts on the frontend, I don't want to include the passwords for security reasons. To achieve this, I attempted to ...

Utilizing a setTimeout function within a nested function in JavaScript

Recently delving into the world of JavaScript, I encountered an issue with a code snippet that goes like this: function job1() { var subText1 = ""; var subText2 = ""; var text = ""; var vocabulary = "ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijkl ...

Having trouble generating an array for checkboxes using jQuery, AJAX, and PHP

I'm almost there, but there's something missing. I'm attempting to send variables from multiple checkboxes to a PHP page using jQuery. This is my code: <div id="students"> <div class="field"> <label> ...

Error: 'fs' module not found in React.js and cannot be resolved

Encountering issues with tatum io v1 + react? Developers have acknowledged that it's a react problem which will be addressed in V2. In the meantime, you can utilize tatum io V1 with node js. I've included all dependencies that could potentially ...

Encountering issues with the addEventListener function in a React application

Here's the scenario: I'm currently working on integrating a custom web component into a React application and I'm facing some challenges when it comes to handling events from this web component. It seems that the usual way of handling events ...

Chat lines in Chrome displaying double entries - troubleshooting needed

I developed a chat plugin for my website with a simple HTML structure: <div id="div_chat"> <ul id="ul_chat"> </ul> </div> <div id="div_inputchatline"> <input type="text" id="input_chatline" name="input_chatline" val ...

employing constructor objects within classes

I am attempting to utilize a class with a constructor object inside another class. How should I properly invoke this class? For example, how can I use Class 1 within Class 2? Below is an instance where an object is being created from a response obtained f ...

Mapping arrays from objects using Next.js and Typescript

I am trying to create a mapping for the object below using { ...product.images[0] }, { ...product.type[0] }, and { ...product.productPackages[0] } in my code snippet. This is the object I need to map: export const customImage = [ { status: false, ...

Is it appropriate to delete the comma in the Ghost Handlebars Template?

While navigating through the tags, I unexpectedly encountered a comma. This could potentially have an unwanted impact. I attempted to remove the comma, but is there a specific method to eliminate it completely? I referred to the Ghost blog Document for gui ...

What could be causing the issue of why the null check in JavaScript isn't functioning properly

function getProperty(property) { console.log(localStorage[property]) //Displays “null” if(localStorage[property] == null) { console.log('Null check') return false; } return localStorage[property]; } The log outputs "nu ...

Checking the list box and radio button using JavaScript based on their respective IDs

Looking to validate the selection of a listbox and radio button using their respective IDs when a submit action occurs. When testing in the browser, no alert is being displayed. The goal is to trigger the script upon clicking the submit button to verify ...

Exploring the correct navigation of page objects through Protractor using TypeScript

I'm working on setting up a protractor test suite with TypeScript and running into an issue involving chaining of pageObjects for multiple pages. I haven't seen any examples that deal with this specific scenario. I've simplified the example ...

Master the art of adjusting chart width on angular-chart with the help of chart.js

I am currently using angular-chart along with Angular and chart.js to create multiple charts on a single page. However, I am facing an issue where each chart is taking up the entire width of the screen. I have tried various methods to limit the width based ...