What is the best way to retrieve an object from a loop only once the data is fully prepared?

Hey, I'm just stepping into the world of async functions and I could use some help. My goal is to return an object called name_dates, but unfortunately when I check the console it's empty. Can you take a look at my code?

Here's what I have so far:

async findAllScribesWithProfileName() {

...


let name: string;
let dates: Date[];

type NameDates = { display_name: string; created: Date[] };
const name_dates = <NameDates[]>{};


 owners.forEach(async (owner, ownerIdx) => {
    name = (await this.profileService.getById(owner)).display_name;
    dates = scribes
      .filter((scribe) => scribe.owner == owner)
      .map((s) => s.created);

    name_dates[ownerIdx] = {
       display_name: name,
       created: dates,
     };
  });

 return name_dates;
}

I attempted to place the return statement inside the owners.forEach loop, but unfortunately that didn't give me the results I was hoping for.

Answer №1

To efficiently handle multiple asynchronous tasks in JavaScript, you can leverage the power of Promise.all and utilize array mapping for simultaneous execution:

await Promise.all(
  owners.map(async (owner, ownerIdx) => {
    name = (await this.profileService.getById(owner)).display_name;
    dates = scribes
      .filter((scribe) => scribe.owner == owner)
      .map((s) => s.created);

    name_dates[ownerIdx] = {
      display_name: name,
      created: dates,
    };
  })
);

return name_dates;

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

Merging objects with identical keys into a single object within an array using Typescript

Here is the array that I am working with: Arr = [{ code: "code1", id: "14", count: 24}, {code: "code1", id: "14", count: 37}] My objective is to consolidate this into a new array like so: Arr = [{ code: "code1& ...

When I attempt to add a todo item by clicking, the Url value is displayed as "undefined"

I am facing an issue with my household app where, upon clicking the button to navigate to the addtodo page, the URL specific to the user's house is getting lost. This results in the todolist being stored as undefined on Firebase instead of under the c ...

What is the best way to manage data types using express middleware?

In my Node.js project, I am utilizing Typescript. When working with Express middleware, there is often a need to transform the Request object. Unfortunately, with Typescript, it can be challenging to track how exactly the Request object was transformed. If ...

What is the best way to ensure a specific row remains at the bottom of an Angular table with Material when sorting?

My data table contains a list of items with a row at the end showing the totals. | name | value1 | value2 | --------------------------- | Emily | 3 | 5 | | Finn | 4 | 6 | | Grace | 1 | 3 | | TOTAL | 8 | 14 | I&apos ...

Having trouble getting my asynchronous promise to work properly

I am currently working on implementing a login server function and I am struggling to understand why the promise I'm making is not being called. My setup involves using MongoDB with Mongoose as the backend, which is connected to using User.findOne. A ...

Importing Heroicons dynamically in Next.js for more flexibility

In my Next.js project, I decided to use heroicons but faced a challenge with dynamic imports. The current version does not support passing the icon name directly to the component, so I created my own workaround. // HeroIcon.tsx import * as SolidIcons from ...

How can a nullable variable be converted into an interface in TypeScript?

Encountered an issue while working on a vue3.x typescript project. The vue file structure is as follows: <template> <Comp ref="compRef" /> </template> <script lang="ts" setup> import {ref} from "vue& ...

Inquiry regarding modules in Javascript/Typescript: export/import and declarations of functions/objects

I'm fresh to the realm of TypeScript and modules. I have here a file/module that has got me puzzled, and I could really use some guidance on deciphering it: export default function MyAdapter (client: Pool): AdapterType { return { async foo ( ...

Execute a series of Promises (or Deferreds) consecutively and have the flexibility to pause or stop at any point

Having an issue here. Need to make numerous consecutive http calls and the ability to stop the process at any point in time. The current solution I have involves jQuery and Deferreds, but it lacks proper interruption handling (still haven't transition ...

Tips for implementing assertions within the syntax of destructuring?

How can I implement type assertion in destructuring with Typescript? type StringOrNumber = string | number const obj = { foo: 123 as StringOrNumber } const { foo } = obj I've been struggling to find a simple way to apply the number type assertio ...

Angular findIndex troubleshooting: solutions and tips

INFORMATION = { code: 'no1', name: 'Room 1', room: { id: 'num1', class: 'school 1' } }; DATABASE = [{ code: 'no1', name: 'Room 1', room: { id: 'num1', ...

Determining the height of dynamically rendered child elements in a React application

Looking for a way to dynamically adjust the heights of elements based on other element heights? Struggling with getting references to the "source" objects without ending up in an infinite loop? Here's what I've attempted so far. TimelineData cons ...

Guide on Executing a Callback Function Once an Asynchronous For Loop Completes

Is there a way to trigger a callback function in the scan function after the for await loop completes? let personObj = {}; let personArray = []; async function scan() { for await (const person of mapper.scan({valueConstructor: Person})) { ...

Issue with MathJax rendering within an Angular5 Div that's being observed

I am trying to figure out how to enable MathJax to convert TeX to HTML for elements nested within my div. Here is the current content of app.component.html: <p> When \(a \ne\) It works baby </p> <div class="topnav"> ...

typescript code may not display a preview image

I recently came across a helpful link on Stack Overflow for converting an image to a byte array in Angular using TypeScript Convert an Image to byte array in Angular (typescript) However, I encountered an issue where the src attribute is not binding to t ...

Speedy Typescript inquiry query

I'm currently in the process of creating a basic endpoint by following the Fastify with Typescript documentation linked below: https://www.fastify.io/docs/v3.1.x/TypeScript/ export default async function customEndpoint(fastify: any) { const My ...

Can one bring in a JavaScript function using webpack?

I have a unique JS library called: say-my-greeting.js function SayMyGreeting (greeting) { alert(greeting); } Now I want to incorporate this function in another (.ts) file; special-class.ts import SayMyGreeting from './say-my-greeting.js' ex ...

The expected function is being executed, yet none of the inner functions are invoked

Currently, I am working on unit tests for an Angular application using Jasmine and Karma. One particular unit test involves opening a modal, changing values in a form, and saving them. Everything goes smoothly until it reaches the promise inside the open() ...

Ensure that the hook component has completed updating before providing the value to the form

Lately, I've encountered an issue that's been bothering me. I'm trying to set up a simple panel for adding new articles or news to my app using Firebase. To achieve this, I created a custom hook to fetch the highest current article ID, which ...

Firebase Promise not running as expected

Here is a method that I am having trouble with: async signinUser(email: string, password: string) { return firebase.auth().signInWithEmailAndPassword(email, password) .then( response => { console.log(response); ...