Categories for the Promise.all() function

I'm feeling lost trying to understand the differences between the request tuple return type and Promise.all(). This is driving me crazy.

Any suggestions?

const createPromises = async (utteranceObject: Array<string[]>): 
  Promise<Array<[string, Blob]>> => {
  const promises = utteranceObject.map((keyValue) => {
    return buildAudioFetchRequests(keyValue[0], keyValue[1]);
  });
  return Promise.all<Promise<[string, Blob]>[]>(promises);
};

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

https://i.sstatic.net/9D1Ot.png

Answer №1

Your code contains a misunderstanding related to the variable name promises.

The function buildAudioFetchRequests does not return a promise, but rather a tuple consisting of a key and a promise. When you await this value, it returns the same tuple because await does not inspect the contents of objects or arrays.

Considering the return types in your code, it appears that you intend to await all the promises returned as part of the tuple. You can achieve this with the following approach:

const createPromises = async (utteranceObject: Array<string[]>): 
  Promise<Array<[string, Blob]>> => {

  const requests = utteranceObject.map((keyValue) => {
    return buildAudioFetchRequests(keyValue[0], keyValue[1]);
  });

  const promises = requests.map((req) => req[1]);

  return Promise.all(promises);
};

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

In response to Bergi's comment:

Why bother returning the key in a tuple from buildAudioFetchRequests if it is not being used at all?

If you are indeed not utilizing the key from the return value of that function anywhere, you could simplify the code like this:

const createPromises = async (utteranceObject: Array<string[]>): 
  Promise<Array<[string, Blob]>> => {
  const promises = utteranceObject.map((keyValue) => {
    return buildAudioFetchRequests(keyValue[0], keyValue[1]);
  });

  return Promise.all(promises);
};

const buildAudioFetchRequests = (key: string, url: string): 
     // Adjust the return type here
     Promise<[string, Blob]> => {

  // Update the return value accordingly
  return useAuthenticatedFetch(url, { initialCache: false });
};

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

What is the best way to access the data stored within a Promise object in a React application?

Below is the snippet of my code that handles parsing application data: async function parseApplication(data: Application) { const fieldGroupValues = {}; for (const group of Object.keys(data.mappedFieldGroupValues)) { const groupValue = data.mappedF ...

What is the best way to retrieve the value of the selected mat-option?

I've been struggling to extract the selected value of a mat-option using this specific HTML and TypeScript code. html <mat-form-field appearance="outline" floatLabel="always"> <mat-label>TRA Type</mat-label> ...

Using Firebase: retrieving getAdditionalUserInfo in onCreate of a Firebase Cloud function

Can anyone help me figure out how to retrieve extra data from a SAML login provider in the backend (firebase functions)? I can see the data on the client side but I'm struggling to access it in the backend. I've specified these dependencies for ...

What is the rationale behind TypeScript's decision to implement two checks for its optional chaining and null-coalescing operators during compilation?

What is the reason behind the way the TypeScript compiler translates its optional chaining and null-coalescing operators, found here, from: // x?.y x === null || x === void 0 ? void 0 : x.y; // x ?? y x !== null && x !== void 0 ? x : y as opposed ...

Jest test encountering an issue where FileReader, File, and TextDecoder are not defined

While I have primarily used Jasmine for tests in the past, I am now experimenting with Jest. However, I have encountered an issue where classes like FileReader, File, and TextDecoder are not defined in my tests. How can I incorporate these classes with t ...

Tips for incorporating asynchronous page components as a child element in next.js?

Utilizing the latest functionality in next.js for server-side rendering, I am converting my component to be async as per the documentation. Here is a simple example of my page component: export default async function Home() { const res = await fetch( ...

When using the `create-react-app` command with the `--typescript` flag, you may encounter an issue when attempting to compile namespaces with the `--

I started a project using npx create-react-app my-app-ts --typescript, then I added two new files, sw-build.js and sw.js in the src/ directory. The content of these files was taken from the discussion on Workbox guidelines at (Guidlines for Using Workbox) ...

Populate a map<object, string> with values from an Angular 6 form

I'm currently setting keys and values into a map from a form, checking for validation if the field is not null for each one. I am seeking a more efficient solution to streamline my code as I have over 10 fields to handle... Below is an excerpt of my ...

Combine a constant interface with a generic function to create a unique generic interface

When dealing with legacy code that utilizes a const in the following pattern: const fnUsedInSetPrototypeOf = { equalityComparer<T>(a: T, b: T) { return a === b }, otherFn<T> (this: T) { /*...*/ }, // ... other things, all along the ...

How can I populate an array using values from a different array in Angular?

I am facing an issue with populating three other arrays based on the property 'game type' from my array called 'my games'. Here is an example of the structure of the 'my games' array: hideScore: true, started: true, startedAt: ...

Angular 4 scatter chart with multiple data points using Google charts

I'm currently developing a scatter graph in Angular 4 using ng2-google-charts from https://www.npmjs.com/package/ng2-google-charts It seems like this is essentially a wrapper for Google Chart Service. The graph looks great with a few values, but whe ...

Converting a nested JSON object into a specific structure using TypeScript

In the process of developing a React app with TypeScript, I encountered a challenging task involving formatting a complex nested JSON object into a specific structure. const data = { "aaa": { "aa": { "xxx&qu ...

Eradicate lines that are empty

I have a list of user roles that I need to display in a dropdown menu: export enum UserRoleType { masterAdmin = 'ROLE_MASTER_ADMIN' merchantAdmin = 'ROLE_MERCHANT_ADMIN' resellerAdmin = 'ROLE_RESELLER_ADMIN' } export c ...

How can you debug a Node.js CLI tool using WebStorm?

Struggling to develop a CLI tool using TypeScript within WebStorm as my IDE. No matter what I try, debugging just won't work for me. My journey in Node.js CLI programming started with this tutorial. Successfully transpiling the TS source with npx tsc, ...

bundle.js encountered a TypeError when attempting to read a property that was undefined, specifically while trying to access the PriceIndexationDataControlStandard

In the midst of developing a React component using the Microsoft PCF Framework, I encountered a perplexing error seemingly out of the blue. While making changes in TypeScript without even executing any build commands, the rendering of my component suddenly ...

Nuxt - It is not possible to use useContext() within a watch() callback

I'm currently utilizing version 0.33.1 of @nuxtjs/composition-api along with Nuxt 2. Here's a snippet from my component: import { defineComponent, useContext, useRoute, watch } from '@nuxtjs/composition-api'; export default defineCompo ...

Angular4 Leaflet Map encountering errors

Here is the template: <div id="mapid" style="height: 500px"></div> After installing Leaflet and the typings for Leaflet, I encountered an error stating that the map container was not found. To solve this, I added its import. This is the cont ...

What is the reason behind TypeScript requiring me to initialize a property even though I am retrieving its value from a local reference?

I am just beginning to explore Angular. This is the template for my custom component: <div class="row"> <div class="col-xs-12"> <form action=""> <div class="ro"> <d ...

Expanding the Element prototype with TypeScript

Is there a corresponding TypeScript code to achieve the same functionality as the provided JavaScript snippet below? I am looking to extend the prototype of the HTML DOM element, but I'm struggling to write TypeScript code that accomplishes this with ...

What is preventing me from using property null checking to narrow down types?

Why does TypeScript give an error when using property checking to narrow the type like this? function test2(value:{a:number}|{b:number}){ // `.a` underlined with: "Property a does not exist on type {b:number}" if(value.a != null){ ...