简体   繁体   中英

Can't call array methods on void after using Promise.all to return an array in TypeScript

For reference: How to use Promise.all() with Typescript

I have a TypeScript application that I want to use Promise.all() in.

I create an array of promises, call Promise.all on the array, and then use .then to map an array of the responses.

Later in the application, I call .map again on the array of responses, but TypeScript complains that "Property 'map' does not exist on type 'void | any[]'". (In my actual application, I am calling .filter, but the problem applies to all array methods).

I just can't seem to get around the fact that, for TypeScript, my Promise.all might return void rather than an array of any[].

Here's an example that makes three requests using Axios:

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));

// later on...

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

It's this last line that causes the error "Property 'map' does not exist on type 'void | any[]'. Property 'map' does not exist on type 'void'.ts(2339)".

How can I tell the compiler that my Promise.all is going to result in an array?

As helpfully pointed out by @jcalz, the issue here is the .catch which will return a type of void.

Checking for the existence of the promises array causes the compiler error to go away:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM