I am making 2 API requests in a promise.all() statement followed by a .then() statement to manipulate the data to fit an expected result type. The function works when I launch API requests separately using async/await but using promise.all results in the returned array being of type void. How can I change the response to infer the correct type?
This returns the correct type
async function getUsers() {
const users = await axios.get<User[]>("serverURL/users");
const data = await axios.get<
Array<{ name: string; data: number }>
>("serverURL/data");
const userData = users.data.map(user => {
return {
//logic to manipulate userData
};
});
return userData;
}
promise.all version returns type 'void | type assigned to.then()' which gets the correct data and I can console.log the result to confirm that it follows the expected structure. However the compiler rejects it with the error:
Type 'void | UserData[]' is not assignable to type 'UserData[]'.
const getUsers = async () => {
return Promise
.all([
axios.get<User[]>("serverURL/users"),
axios.get<Array<{ name: string; data: number }>>("serverURL/data")
])
.then <UserData[]>(res => {
const userData = res[0].map(user => {
return {
//logic to manipulate userData
};
});
return userData;
})
.catch(console.error)
}
I have tried using promise.all<any>()
and various other tips I've read but the documentation regarding promise.all with Typescript is quite sparse. I would appreciate if someone could point me in the right direction or tell me what I am doing wrong.
The issue is the catch. When you catch/handle a promise rejection you are returning nothing/void causing the promise to be fulfilled. console.error
returns void, but does not rethrow. Therefore your return will return a UserData | void
. Throwing after the catch should fix this.