Unable to invoke array functions on undefined after utilizing Promise.all to generate an array within TypeScript

For more information, you can check out this post on Stack Overflow: How to use Promise.all() with Typescript

In my TypeScript project, I am trying to implement Promise.all().

I have an array of promises that I pass to Promise.all(), then use .then() to handle the responses.

However, when I try to use .map() on the responses later in the code, TypeScript shows an error message stating "Property 'map' does not exist on type 'void | any[]'". This issue arises regardless of which array method I use.

The problem seems to be that TypeScript expects Promise.all() to potentially return void instead of an array of any[].

Here is a sample code snippet where Axios is used to make three requests:

const requests = [1, 2, 3].map((request) =>
 axios.get(`http://localhost:3000/test${request}`)
);

const promises = await Promise.all(requests)
  .then((responses) => responses.map((response) => response.data))
  .catch(({ message }) => console.log(message));

// further down...

const responses = promises.map(promise => promise.hello);

The error "Property 'map' does not exist on type 'void | any[]'. Property 'map' does not exist on type 'void'.ts(2339)" occurs at the last line.

Is there a way to inform the compiler that the result of my Promise.all() will be an array?

Answer №1

Thanks to the insights from @jcalz, it has been noted that the problem lies within the .catch statement returning a void type.

To resolve the compiler error, we can simply check for the presence of the promises array:

let responses;
if(promises) {
  responses = promises.map(response => response.hello);
}

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

Despite successfully passing props into V-for, the output does not display the props as expected

I've been attempting to accomplish a straightforward task, but for some reason, it's not working and I can't figure out why. Within the parent component, App.vue, I have the following: data() { return { servers: [ { ...

Issue encountered while attempting to include a background image in React JS

I encountered an issue when attempting to include a background image in react js. ./src/index.css (./node_modules/css-loader/dist/cjs.js??ref--5-oneOf-4-1!./node_modules/postcss-loader/src??postcss!./src/index.css) Unable to locate module: An attem ...

incorporating my unique typographic styles into the MUI framework

I'm currently working on customizing the typography for my TypeScript Next.js project. Unfortunately, I am facing difficulties in configuring my code properly, which is causing it to not work as expected. Can someone kindly provide assistance or guida ...

What is the best method for storing a model in a database?

Hello, I am currently attempting to save a model to the database. I am simply inputting the value of a title in order to save it, as my id is set to auto increment. However, I have encountered an issue where my attempts have been unsuccessful. Can someone ...

Execute the function if the text or value begins with a certain character

I'm trying to determine whether the text within a span starts with the letter "x" and then execute a function. I've come across using "^" in strings for this purpose, but am having trouble implementing it to check the text... <span>xfoo&l ...

Configuring Google Maps API (including charts) for maximum height of 100%

I am having trouble getting my map to display at 100% height using the Google Maps API. I've encountered similar issues in the past with the Google Charts API as well. From what I've gathered, it seems like setting the height of the html and bod ...

Issues encountered while sending HTML Form data to MySQL with Node JS

I have been experimenting with a basic html form to mysql using nodejs, but unfortunately it is not functioning as expected. The HTML file is named index.html and the Node.js file is called test.js. Below you can find my code: My HTML <!DOCTYPE html&g ...

How can I efficiently include all css from node_modules in vuejs?

For my Vue.js app built with the webpack template and vuetify, I am starting by importing the vuetify css in my App.vue. <style> @import '../node_modules/vuetify/dist/vuetify.min.css' </style> I'm wondering if this is the c ...

Express JS causing NodeJS error | "Issue with setting headers: Unable to set headers after they have been sent to the client"

As I embark on my journey to learn the fundamentals of API development, I am following a tutorial on YouTube by Ania Kubow. The tutorial utilizes three JavaScript libraries: ExpressJS, Cheerio, and Axios. While I have been able to grasp the concepts being ...

Using JavaScript, is there a way to modify a JSON parameter within an API?

My API provides JSON data structured like this: [{"NAME":"john","SURNAME":"johny","ADULT":"3","CHILD":"3","BABY":"0",}] In my JavaScript function, I need to send a request to a web service that will update the value of "BABY" from "0" to "1". Can this be ...

Using Vue.js to conditionally render content based on changes in a variable

I am facing a challenge in rendering a new element once the boolean variable waiting changes to true. The issue arises when transitioning from one v-if statement to another, as the boolean does not update until the first statement is completed. How can I s ...

Tips for inserting an element into a div only if both the element and div share the same id using JavaScript

Looking to drag and drop an element into a div with multiple divs, but only allowing the drop if the IDs of the element and the div match. Trying to retrieve the ID of the div where the image is being dragged, compare it with the ID of the dragged image, a ...

Consecutive pair of XMLHttpRequest requests

Is it possible to create a functionality where the page index.php sends a Javascript variable called idToken, which is then received in another page called token.php using Javascript as well? In the token.php page, there will be more code that processes ...

When attempting to reference a custom module within a React application, the error message "moment is not a function" may appear

I am facing an issue while trying to integrate a custom module I developed into a basic React application using react-boilerplate. Upon importing the module, I encountered an error stating that the moment function within the module is undefined. Here is t ...

What are the recommended margins for various alphabets?

When displaying text, some alphabets take up more space than others. So how can I adjust the white space between elements '#re1' and '#re2' automatically in the scenario described below? In this code snippet, what is the best way to ad ...

The inferred type of a TypeScript promise resolved incorrectly by using the output value from a callback function

Although some sections of the code pertain to AmCharts, the primary focus of the question is related to TypeScript itself. The JavaScript functions within the AmCharts library perform the following tasks: export function createDeferred(callback, scope) { ...

Is it possible to execute two separate functions within a single Node.js file using distinct command line prompts?

In my project, I have a .js file that imports an NPM package and contains two functions that utilize that package: //replacePaths.js import {replaceInFile} from 'replace-in-file'; async function replace() { const options = { files: &a ...

What is the best way to incorporate a Video Player into React-JSX?

I am brand new to React/JSX and coding in general. Please excuse any lack of clarity in my question. Currently, I am working on a web app project for an exam. I need to add a video player, but I am struggling to find one that fits with my code. I am using ...

Node.js frequently returns null with its url methods

I'm having some trouble getting node.js to display the HTTP request properties in the browser. I've tried printing the properties of the request URL, but they either show up as null or don't display at all. Below is the code for the server ( ...

Unable to receive comment reply through Ajax without refreshing the comment section

I'm facing an issue where I cannot retrieve comment replies via Ajax under comments, even though the replies are successfully saved in the database. Oddly enough, upon refreshing the Index.php page, the replies display correctly. I suspect the problem ...