0

отметил место где не могу понять какой тип поставить потому как вoзможных вариантов возврата несколько либо TUser или TAddress или обе разом или null в типе Promise.all

и буду рад замечаниям на счет кода

    type TUser = {
        name: 'a',
        surname: 'b'
    }

    type TAddress = {
        address: 'x'
    }
    const getList = async (resource: string, params: GetListParams) => {
    const finishedResult = {
        data: [],
        total: 0,
    };
    const {body: { result, totalCount }} = await CustomerService.getCustomerPage()
    finishedResult.total = totalCount
    //вот тут каким будет возвращаемый тип?
    const promises = result.map(({addressId, userId}):какой возвращаемый тип? => {
        if(!addressId && !userId) {
            return null
        }
        if(addressId && userId) {
            return Promise.all([
                UserService.getUserById(userId),
                AddressService.getAddressById(addressId)
            ])
        }
        if(!addressId) {
            return Promise.all([UserService.getUserById(userId)])
        }
        if(!userId) {
            return Promise.all([AddressService.getAddressById(addressId)])
        }
    })
    promises.filter(e => e !== null)
    //вид данных внизу
    const res = await Promise.all(promises)
    res.forEach(arr => {
        let finalRes = {}
        arr.forEach(({status, body}) => {
            if(status === 'success'){
                finalRes = {...finalRes,...body}
            }
        })
        if(isObjectWithProperties(finalRes)){
            finishedResult.data.push(finalRes)
        }
    })
    return Promise.resolve(finishedResult);
}

данные в res

const res = [
[
    {
        status: '',
        body: {}
    },
    {
        status: '',
        body: {}
    },
],
[
    {
        status: '',
        body: {}
    },
    {
        status: '',
        body: {}
    },
],

]

0

1 ответ 1

1

По коду - зачем мешать Promise и async\await? Используйте что-то одно.

Тип можете указать как Promise<(TUser | TAddress)[] | null>. Или, если более точно Promise<[TUser | TAddress, TUser | TAddress] | null>

type TUser = {
    name: 'a',
    surname: 'b'
}

type TAddress = {
    address: 'x'
}

const func = async ():Promise<(TUser | TAddress)[] | null>=>null;
~ async function(){
const res = await func();
}();

https://www.typescriptlang.org/play?#code/AQ4FwTwBwU2AVAqgZxgJ2AXmAbwFCiHAB2AhgLYwBcwA5KbQDQFEjICuaZlNtARrRYgAvniHhoceAEEAJrLQxkyLLnGFS8xct4APQYVHiAxgHtiyMMABm7YsdWlkEe8AAUASioAFNKfIAlqgAPG5IqBgAPghyCkrIHgDaALrA0cTsADaZAHyYORnZANziAH7ATi4OtvZgAeae+IRmFlbajgDupAFWNcaeJYYDQA

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.