Using TypeScript to asynchronously combine multiple Promises with the await keyword

In my code, I have a variable that combines multiple promises using async/await and concatenates them into a single object

const traversals = (await traverseSchemas({filename:"my-validation-schema.json"}).concat([
      _.zipObject(
        ["id-1", "id-2"],
        [
          await loadSchema({
            filename: "schema-1.json"
          }),
          await loadSchema({
            filename: "schema-2.json"
          }),
        ]
      ),
    ]);  

The traverseSchemas function returns an array object like this:

[{"key1":{object}}, {"key2": {object}}]

I am currently looking into whether there is a way to apply the await keyword only at the traversals level so that all promised data gets fulfilled, or if there is a better way to refactor this code.

Answer №1

When handling multiple promises where the result is independent of each other, utilizing Promise.all allows for parallel execution without dependency on individual outcomes. This efficient approach involves a single await and synchronously combines the awaited values using return ....

async function processPromises() {
  const [data1, data2, data3] = await Promise.all([
    fetchData("url-1"),
    fetchData("url-2"),
    fetchData("url-3"),
  ])

  return [
    ...data1,
    _.zipObject(["key-1", "key-2"], [data2, data3])
  ]
}

If top-level await is accessible or within another async function, defining const results = ... can replace the return statement -

const [data1, data2, data3] = await Promise.all([
  fetchData("url-1"),
  fetchData("url-2"),
  fetchData("url-3"),
])

const results = [
  ...data1,
  _.zipObject(["key-1", "key-2"], [data2, data3])
]

Answer №2

There are several choices available.

Generally, simple code is more understandable. Therefore, I suggest using something like this:

const validationSchemas = await traverseSchemas({ filename:"my-validation-schema.json" })
const schema1 = { "id-1": await loadSchema({ filename: "schema1-json" });
const schema2 = { "id-2": await loadSchema({ filename: "schema2-json" });

const traversals = [ ...fetchedSchemas, schema1, schema2 ];

If you wish to make the awaits parallelizable, you could prepare them first, then request via Promise.all and combine them afterwards:

const tasks = [
    traverseSchemas({ filename:"my-validation-schema.json" }),
    loadSchema({ filename: "schema1-json" }),
    loadSchema({ filename: "schema2-json" })
];

const [validationSchemas, schema1Value, schema2Value] = await Promise.all(tasks);

const traversals = [
    ...validationSchemas,
    { 'id-1': schema1Value },
    { 'id-2': schema2Value }
];

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

Problem with loading image from local path in Angular 7

I'm having trouble loading images from a local path in my project. The images are not rendering, but they do load from the internet. Can someone please help me figure out how to load images from a local path? I have already created a folder for the im ...

Exporting ExpressJS from a TypeScript wrapper in NodeJS

I've developed a custom ExpressJS wrapper on a private npm repository and I'm looking to export both my library and ExpressJS itself. Here's an example: index.ts export { myExpress } from './my-express'; // my custom express wrap ...

I need help differentiating "namespace" from "static attributes" in TypeScript

Separating namespace from static properties in TypeScript can sometimes be tricky. error: 'ClassA' only refers to a type, but is being used as a namespace here. class ClassA { static ClassB = class { }; } type T = ClassA // ok type T = C ...

Encountering an error when trying to set data in a Firestore document with a customized JavaScript object: "Invalid data provided for function DocumentReference.set()"

For my initial project, I need help in identifying where the issue lies. Firstly, I have a function that adds data to Firebase: addpost() { let newposts = new Posts( this.addForm.value ) this.postsservice.addPosts(newposts); } Ne ...

Building Silent Authentication in React Native with the help of Auth0: A Step-by-Step Guide

I am currently working on my first React Native app, and I have integrated Auth0 for authentication purposes. My goal is to implement silent authentication using refresh tokens. So far, I have attempted to use the checkSession() method but encountered an ...

In Angular and Typescript, adjusting the index in one dropdown will automatically update the selected option in another dropdown

I'm a newcomer to Angular and I could use some assistance with the following requirement: In my Angular template, I have two dropdowns. I want the selection in one dropdown to automatically reflect in the other dropdown. Both dropdowns pull their val ...

Show a few values as a string in Angular using Typescript

I am working with JSON data and I want to know how to display hobbies without including the word "all" in an Angular/TypeScript application. { "Name": "Mustermann1", "Vorname": "Max1", "maennlich& ...

Tips for creating dynamic alerts using mui v5 Snackbar

My goal is to call an API and perform several actions. After each action, I want to display the response in a Snackbar or alert. Despite iterating through the messages in a map, I'm only able to show the first response and none of the others. Here is ...

The typings for object properties in Typescript

I recently encountered a function call in my code: var myVar = myFunction({ property: 'prop', functionProperty() { console.log(this.property); }, functionProperty2() { this.functionProperty(); } }); I' ...

Expanding the typings for an established component in DefinitelyTyped

Is there a way to define new typings for additional props in DefinitelyTyped? After updating the material-ui library with some new props for the SelectField component, I realized that the typings in DefinitelyTyped are outdated. Is it possible to extend th ...

Having trouble with ngx-pagination's next page button not responding when clicked?

I am experiencing issues with pagination. The next page button does not function as expected, and clicking on the page number also does not work. Below is the code snippet and a Demo link for your reference. HTML <table mat-table [dataSou ...

Issue with Nestjs validate function in conjunction with JWT authentication

I am currently implementing jwt in nest by following this guide Everything seems to be working fine, except for the validate function in jwt.strategy.ts This is the code from my jwt.strategy.ts file: import { Injectable, UnauthorizedException } from &ap ...

I'm having trouble retrieving the information as it is showing as undefined. Can anyone offer any advice?

Attempting to extract specific information from an API response has proven challenging. Despite my efforts to isolate the desired data, all listed details appear as undefined. import { HttpClient } from '@angular/common/http'; import { Injectable ...

Standardize API response using NgRX Entity

Can the NgRx Entity library normalize a nested JSON api response? If I have data structured like this: [ { "id": "1", "title": "My first post!", "author": { "id": "123", "name": "Paul" }, ...

Unable to install Typescript using npm

I recently started a tutorial on Typescript and wanted to install it globally using npm. npm i typescript -g However, I encountered an issue where the installation gets stuck on the first line and displays the following message: (⠂⠂⠂⠂⠂⠂⠂⠂ ...

Utilizing the useSelect hook in Typescript to create custom types for WordPress Gutenberg, specifically targeting the core/editor

As I delve into development with WordPress and the Gutenberg editor, my goal is to incorporate TypeScript into the mix. However, I encounter a type error when trying to utilize the useSelect() hook in conjunction with an associated function from the core/e ...

How can I redirect a page using an axios interceptor in Next.js?

Is there a way to redirect the page in an axios interceptor when dealing with server-side rendering limitations? Unfortunately, I am unable to access the server side context in the axios interceptor. I have tried using next/router but it only works on the ...

Give it a little time before uploading a widget onto the page

As a newcomer to programming, I recently came across this code from an open source project. I am in the process of loading a widget onto a website. Instead of having the widget load instantly, I would like it to wait 10 seconds before displaying. Below i ...

What is the best way to execute a method in a component for each iteration in an *ngFor loop in Angular 2

Is there a way to call a method for each iteration of *ngFor and pass the iterated variable as a parameter? For example: <li *ngFor="let element of componentModel | keys">{{element.key}}--{{element.value}}</li> Then, in the component, I have ...

I am facing an issue with my useFetch hook causing excessive re-renders

I'm currently working on abstracting my fetch function into a custom hook for my Expo React Native application. The goal is to enable the fetch function to handle POST requests. Initially, I attempted to utilize and modify the useHook() effect availab ...