简体   繁体   中英

Returning the correct type from Promise.all in TypeScript

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 UserData | void . Throwing after the catch should fix this.

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