Assigning unique identifiers to the data retrieved from Promise.all

I'm currently facing an issue with handling promises in my code - specifically, the Promises returned are not correctly mapped to the utteranceId as desired. I want to ensure that the ids are preserved for the data being returned. Even after using Object.entries(utteranceObject) to wrap my object.

When I log keyValue after applying

Object.entries(utteranceObject).map(keyValue)
, the data appears to be formatted correctly as [id, url]. How should it be formatted when passing to Promise.all()?


const getUtterancesAudio = async (
 utterances: { utteranceId: string, interviewId: string }[]): Promise<void> => {
const config = useRuntimeConfig();

const mapped = utterances.map((u) => {
return { id: u.utteranceId, url: `${config.public.apiBase}/utterance/182bd8fe-f57d- 
4595-b8d7-649ff8ca6d62/interview/665a799a-883b-4b20-9460-3eee486516a8/audio` };
});

const flatten = mapped.map(Object.values);
const forPromisesEntries = Object.fromEntries(flatten);
const getResults = await createPromises(forPromisesEntries);
};



const createPromises = async (utteranceObject: Record<string, string>): 
 Promise<unknown> => {
 const promises = Object.entries(utteranceObject).map(keyValue => 

 buildAudioFetchRequests(keyValue[0], keyValue[1]));

   return Promise.all(promises);
};


const buildAudioFetchRequests = async (key: string, url: string): Promise<unknown> => 
{
 return [key, useAuthenticatedFetch(url, { initialCache: false }]);
};

Answer №1

In my opinion, there is potential to significantly simplify the code. From what I gather, the original poster starts with an array of utterance IDs structured like this:

[ { utteranceId: '123' }, { utteranceId: '456' }, ...

The desired outcome is to generate a result resembling this:

[ { id: '123', result: 'result of api call for 123' }, ...

To begin, create a function that constructs the desired object by invoking the API and linking the response with the input parameter as shown below...

const fetchUtterance = async (id: string, url:string):Promise<unknown> => {
  let response = await useAuthenticatedFetch(url, { initialCache: false });
  return { id, response };  // highlight lies here
}

Simply iterate over the array of utterance IDs to call this function and receive an array of promises. Then, await all promises using all()...

const getUtterancesAudio = async (utterances) => {
    const config = useRuntimeConfig();
    const basePath = '/utterance/182bd8fe-f57d-4595-b8d7-649ff8ca6d62/interview/665a799a-883b-4b20-9460-3eee486516a8/audio';
  
    const promises = utterances.map((u) => {
      return fetchUtteranceID(u.utteranceId, `${config.public.apiBase}${basePath}`);
    });
  
    const results = await Promise.all(promises);
    console.log(results);
};

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

Is it possible for a class that implements an interface to have additional fields not defined in the parent interface?

Looking at the code snippet below, my aim is to ensure that all classes which implement InterfaceParent must have a method called add that takes an instance of either InterfaceParent or its implementing class as input and returns an instance of InterfacePa ...

What is the best way to ensure that a specific data type is used for a key in an object?

Struggling to create a versatile function that can efficiently sort string properties of objects using String.localCompare. However, TypeScript seems not to acknowledge that a[key] and b[key] should be treated as strings. How can I resolve this issue in T ...

Ways to populate missing cells with a default hyphen symbol

Looking for a way to default empty cells in my primeng datatable to '-'. Consider the following data: [ { 'column': null }, { 'column': { 'name': 'A' } }, { 'column': { 'name': ...

What is the reasoning behind Typescript's belief that the symbol 'name' is consistently present?

When working with Typescript, I've noticed that my code is sometimes accepted by the compiler even when I mistakenly write name instead of someObject.name. To test this behavior, I compiled a file with just console.log(name) and surprisingly, the Typ ...

Incompatible TypeScript function declarations

Here's an example code snippet that is causing me some confusion due to an error. In the setFilter method, I have specified the type of T as Product. Therefore, I would expect to be able to successfully set the filter, since both T and Product share ...

Validating a field conditionally upon submission

Adding a required validation conditionally to the "imageString" field upon submission, but the expected required validation is not being set. Initializing the form. constructor(){ this.poeForm = this.fb.group({ imageString: [""], imageFileNam ...

"Protractor encountered an issue when navigating to the most up-to-date Angular section in our

We are in the process of upgrading our application from AngularJS to the latest version of Angular. I am currently working on writing tests that transition from the AngularJS version of the app to the admin application, which is built using the latest ver ...

Utilize environment.ts in Angular library module for importation purposes

I have an angular monorepo and I'm looking to reuse a specific module across multiple projects without duplicating it. The challenge is to use the environment specific to each project, rather than copying and pasting the code into each one. import { e ...

Tips for using the arrow keys to navigate the cursor/caret within an input field

I am trying to create a function that allows the cursor/caret to move inside an input field character by character using the arrow keys (ArrowLeft, ArrowRight) on a keydown event. Current Approach: const handleKeyDown = (e: KeyboardEvent<HTMLInputEle ...

Decorator used in identifying the superclass in Typescript

I am working with an abstract class that looks like this export abstract class Foo { public f1() { } } and I have two classes that extend the base class export class Boo extends Foo { } export class Moo extends Foo { } Recently, I created a custom ...

What is the reason behind angular 4.3's httpclient returning Object instead of any?

The Angular 4.3 update introduces the new HttpClient class, which appears to return Object instead of any as the default type. Is there a specific reason for this decision, especially considering the TypeScript documentation advises against using types li ...

Executing ts-node scripts that leverage imported CSS modules

Is there a way to execute scripts that utilize css modules? I am currently working on a typescript migration script that I would like to execute using ts-node. The ideal scenario would be to keep the script's dependencies separate from the React comp ...

Retrieve the keys of a type by analyzing one of its values

My global type definition consists of an object with keys (referred to as a prop) that must be passed by the user as a parameter to myFunction(), and values that are used solely for type checking within my code. These values can fall into only 3 "possible ...

When using nodejs with sqlite3, the first callback parameter returns the class instance. How can this be resolved in order to prevent any issues?

Exploring a TypeScript class: class Log { public id: number; public text: string; construct(text: string){ this.text = text; } save(){ db.run( `insert into logs(text) values (?) `, this.text, ...

Running promises in sequence with Node.js

Hey there, I'm looking for a way to run promises sequentially in Node.js. In the example below, I am looping through an array of hours and want to fetch results from the database for each hour in the same order as they were retrieved. angular.forEac ...

Conceal pagination when printing - utilizing primeng table

In my application, I have a main component called Bill which includes a button for printing: <button class="btn btn-primary" type="button" (click)="printBill()"> Print </button> I also have a child component named BillProducts that contains a ...

How can we use fetch to grab some data?

I put together an Express application quickly, here's how it looks: const express = require("express"); const app = express(); const port = 3000; app.get("/content/1/", (req, res) => res.send("Thinking about taking out a new loan? Call us today. ...

I encountered some problems with conflicting Angular dependencies, so I decided to delete the node_modules folder

An error has occurred: The module 'H:\All_Files\Scripts\Angular\example\node_modules\source-map\source-map.js' could not be found. Please ensure that the package.json file contains a correct "main" entry. ...

Getting a "function is not defined" error in Angular 6 while using it within a nested function

I'm facing an issue related to typescript, where the following code is causing trouble: private loadTeams = function(){ let token = sessionStorage.getItem('token'); if(token !== undefined && token !== null && token ...

Select all entities in TypeORM except for the ones where the id is not equal to a specific condition

In my scenario, I am dealing with two entities: @Entity() export class Point { @PrimaryGeneratedColumn('uuid') id: string; // some other stuff } @Entity() export class Product { ...