最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Returning the correct type from Promise.all in TypeScript - Stack Overflow

programmeradmin3浏览0评论

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 piler 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.

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 piler 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.

Share Improve this question edited Nov 11, 2020 at 23:50 Thomas Ham asked Nov 11, 2020 at 22:26 Thomas HamThomas Ham 802 silver badges6 bronze badges 2
  • In you second getUsers function im not sure how you are accessing users. You need to destructure the res array to be able to access the users as the first element but Im not seeing. – Brenden Commented Nov 11, 2020 at 23:02
  • @Brenden Yes thanks I missed that while obfuscating the variables because I can't post it directly. I have corrected it but the data from the API is being accessed correctly. It is an issue with the way that Promise.all returns types, not the map function. – Thomas Ham Commented Nov 11, 2020 at 23:49
Add a ment  | 

1 Answer 1

Reset to default 6

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.

发布评论

评论列表(0)

  1. 暂无评论