#How do I convert an array of promises to an array of numbers?

9 messages · Page 1 of 1 (latest)

sullen stump
#

I have the following code

        const productPrices = orderBody.productIds.map(async (item) => {
            const product = await prisma.product.findUnique({ where: { id: item }})
            if (!product) return 0
            return product.price
        })

this gives me Promise<number>[]
I want to do this piece for summing all of the prices

const totalAmmount = productPrices.reduce( (count: number, input: number) => count + input )

but typescript is telling me you cant do that because it could be a nullish promise

so how can i make it work?

#

the variable orderBody is an Order type

wooden swift
sullen stump
#

wdym

wooden swift
#

what part(s) of that don't make sense?

radiant pulsar
#

Promise.all turns Array<Promise<T>> into Promise<Array<T>>, exactly what you asked for

digital fern
#

One thing worth pointing out is that Promise.all will reject early if any of the internal promises rejects.
In this case that is not an issue, but there are times where it can be and you would instead use Promise.allSettled if it is available ( allSettled wasn't provived in std lib until ES2020 afaik ).

severe finch
#

Be careful with allSettled because it will hide all errors that could be interesting to log/forward to your analytics server if you have one

digital fern
#

Yeah, the downside is that you have to process through the possibly failed promises and handle them accordingly