1

I have the following code:

this.somePromiseFn<T>  // this fn is actually a promise
.then(res => res as T)
.catch(err => this.handleError<T>(err));

handleError<T>(err: HttpErrorResponse) {
  // do something here
  // and return like
  return {} as T;
}

The above code works fine. But how I can pass the err argument directly to the handleError method without using another callback function. As catch by default passes the err to the callback function, it should also pass the err to the handleCatchError. I want something like:

this.somePromiseFn<T>
.then(res => res as T)
.catch(this.handleCatchError<T>); // this line gives error 'An argument for 'err' was not provided'

But the above code produces the error saying:

Expected 1 argument, but got 0.
An argument for 'err' was not provided.

Though I have visited the following question already:

  1. addEventListener calls the function without me even asking it to
  2. Javascript "addEventListener" Event Fires on Page Load

But the above questions also suggest using another callback function.

X3Vikas
  • 101
  • 2
  • 9
  • This doesn't seem to be a [mcve], unless you count the stackblitz link in a comment on one of the answers. Does `this.someFn().then((r) => console.log(r)).catch(this.cb);` work for you? If not, please edit this question to constitute a reproducible issue. Good luck! – jcalz May 20 '19 at 14:02

3 Answers3

1
this.somePromiseFn<T>
.then(res => res as T)
.catch(this.handleCatchError<T>);

this should work, tried to reproduce the error but it's working see a demo, might be I'm missing something, check and update if necessary.

Sunil Kashyap
  • 2,946
  • 2
  • 15
  • 31
  • Your code is working because you don't have a type variable in your code. See [here](https://stackblitz.com/edit/skdroid-promise-cb-j9zzde?embed=1&file=src/app/app.component.ts), it is not working..! – X3Vikas May 20 '19 at 11:12
1

Based on stackblitz provided by you, see

this.someFn().then(r => console.log(r)).catch(err => this.cb<any>(err));
Adam Kosmala
  • 925
  • 6
  • 9
  • Thanks for your answer, but I am already using the solution you provided..! But I wanted another (sorter) way..! – X3Vikas May 20 '19 at 12:20
0

Don't give generated type and bind "this":

this.somePromiseFn<T>
    .then(res => res as T)
    .catch(this.handleCatchError.bind(this));
yusufcmrt
  • 166
  • 7