admin管理员组

文章数量:1333177

I have this helper function:

export function to(promise: Promise<any>) {
  return promise
    .then((data: any) => [null, data])
    .catch((err: Error) => [err, null]);
}

This function (in theory) should help me catch errors while using await in functions. for example:

const [err, data] = await to(validate(card));

The problem is that on runtime, I get the following error:

to is not a function or its return value is not iterable

While the expected return signature should be Promise<[Error, null]> Promise<[null, Error]>, it looks like returns (again, in theory, because it actually fails): Promise<any[] | Error[]>:

What am I missing?

I have this helper function:

export function to(promise: Promise<any>) {
  return promise
    .then((data: any) => [null, data])
    .catch((err: Error) => [err, null]);
}

This function (in theory) should help me catch errors while using await in functions. for example:

const [err, data] = await to(validate(card));

The problem is that on runtime, I get the following error:

to is not a function or its return value is not iterable

While the expected return signature should be Promise<[Error, null]> Promise<[null, Error]>, it looks like returns (again, in theory, because it actually fails): Promise<any[] | Error[]>:

What am I missing?

Share Improve this question edited Mar 19, 2019 at 7:02 Eliya Cohen asked Mar 19, 2019 at 6:56 Eliya CohenEliya Cohen 11.5k14 gold badges76 silver badges124 bronze badges 4
  • 1 I assume your validate call should be a call to to, right? – ShamPooSham Commented Mar 19, 2019 at 7:00
  • @ShamPooSham you're right. My mistake. I have updated my question – Eliya Cohen Commented Mar 19, 2019 at 7:02
  • Can you put together an small example where this happens? – distante Commented Mar 19, 2019 at 7:07
  • 1 I got exactly the same error in pure Javascript due to a branch in the called function which mistakenly returned a single element instead of an array. – Craig Hicks Commented Aug 11, 2019 at 15:53
Add a ment  | 

1 Answer 1

Reset to default 4

I think the problem is caused by duck typing, TypeScript is not able to guess the return type correctly from the expressions.

You can type it explicit:

function to(promise: Promise<any>): Promise<[Error, any]> {
    return promise
        .then((data: any) => [null, data] as [Error, any])
        .catch((err: Error) => [err, null] as [Error, any]);
}

本文标签: javascriptTypescriptquot is not a function or its return value is not iterablequotStack Overflow