简体   繁体   中英

Promise to Observable does not catch error correctly

I have the following function. I have removed unnecessary code from it to make it simpler to read.

add() {
    const listingId = 'xyz';

    const promise = new Promise((resolve, reject) => {
      reject(Error(`error msg`));
    });

    return from(promise).pipe(
      map(() => listingId),
      catchError(error => of(error.message))
    );
  }

I'm subscribing to the observable like this:

this.service.add().subscribe(
      listingId => {
        console.log(`listingId:`, listingId);
      },
      error => {
        console.log(`Error:`, error);
      },
      () => {
        console.log(`Completed`);
      }
    );

The problem is that the error is catched in the next() instead of error(). The console output is:

listingId: error msg
Completed

It should be:

Error: error msg

What am I doing wrong?

在这一行中catchError(error => of(error.message))使用catchError捕获错误,并且在流切换到of(error.message)catchError类似于switchMap ,您处理错误并切换到另一个可观察到的

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM