-1

I have a problem with type of data in my function promiseRace written in typescript.

function isPromiseLike<T>(U: T | Promise<T>): U is Promise<T> {
  return (U as any).then
}

function promiseRace<T>(values: Array<T | Promise<T>>): Promise<Array<T>> {
  const isArrayEmpty: boolean = Array.isArray(values) && values.length === 0

  return new Promise((resolve, reject) => {
    if (isArrayEmpty) resolve([])

    const promises = values.map((v) => (isPromiseLike(v) ? v : Promise.resolve(v)))

    promises.forEach((promise) => {
      if (promise instanceof Promise) {
        promise.then((data) => resolve(data)).catch((error) => reject(error))
      }
    })
  })
}

In line

promise.then((data) => resolve(data)).catch((error) => reject(error))

second data is underlined and I have a problem: Argument of type 'T' is not assignable to parameter of type 'T[] | PromiseLike<T[]> | undefined'. Type 'T' is not assignable to type 'T[]'.ts(2345). When I make

promise.then((data: any) => resolve(data)).catch((error) => reject(error))

everything looks fine, but it's not a good solution for me. I wanted to do sth like this either

return new Promise<Promise<T>>((resolve, reject) => {

but i have all function underlined then :P

Please about any help!

karo-s
  • 384
  • 2
  • 15

2 Answers2

0

Assuming your code is trying to resolve the promise array when the first promise completes successfully you need to change your code to call the resolve method with an array of data. This is because your returned promise has a generic argument of an array of promises, taken from the return type of your PromiseRace function, so it's resolve method is expecting an array as its argument.

promise.then((data) => resolve([data])).catch((error) => reject(error))

Playground Link

If you take Dane's suggestion above, which seems like a good suggestion, and you change the return type to Promise<T> then you'll just have to change the empty return condition to not return an array

if (isArrayEmpty) resolve()
MacD
  • 426
  • 3
  • 13
-1

You actually dont need function isPromiseLike, your promiseRace function can take values: Array<T> and then you map over it by calling Promise.resolve. It ll behave exactly like you doing in your original post.

Checkout this post for detailed explaination: https://stackoverflow.com/a/27746324/5644120

Vega
  • 27,856
  • 27
  • 95
  • 103
Pritam Kadam
  • 2,388
  • 8
  • 16