1

I am trying to perform a validation and if no exception is thrown, then perform an action. The problem is that the code is async, so the "CompletePlanConfirm()" method is always run, but must be skipped if exception occurs. FirstCheck and secondCheck return Observable. is there a way to accomplish this?

completePlan() {
    try {
        this.validatePlan();
        this.completePlanConfirm();
    } catch (error) {
        throw error
    }
}

validatePlan() {
    this.planService.FirstCheck(this.plan.id).subscribe(
        data => {
            if (!data.result) {
                throw Error('Error 1')
            }
        });
    this.planService.SecondCheck(this.plan.id).subscribe(
        data => {
            if (!data.result) {
                throw Error('Error 2')
            }
        });
}
2
  • How is completePlan supposed to treat errors from validatePlan? catch(error) { throw error } doesn't make much sense. Commented Aug 21, 2020 at 11:11
  • Sample code is a simplification of real one. I currently have a Global error handler for treating errors. Commented Aug 21, 2020 at 12:35

2 Answers 2

1

You can use async / await to make your code synchronous.

Firstly change your validatePlan function so it retuns an observable (and some changes to avoid nested subscription :

validatePlan() {
  return this.planService.FirstCheck(this.plan.id).pipe(
    map(data => {
      if(!data.result) {
      throw Error('Error 1')
      }
    }),
    switchMap(() => this.planService.SecondCheck(this.plan.id))
  ).pipe(
     map(data => {
      if(!data.result) {
      throw Error('Error 1')
      }
    }),
  )
}

Then make completePlan an async function and place the await keyword before the validatePlan function (it needs to be changed into a Promise with .toPromise()

async completePlan() {

try {

  await this.validatePlan().toPromise();
  this.completePlanConfirm();
} catch (error) {
  throw error
}

This way the execution of the function will be synchronous and will wait for validatePlan before going further (so if an error is thrown it'll never try to confirm the plan)

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your time, It seems pretty solid solution. Nevertheless, I went with @xinthose 's solution for simplicity.
0

I would use async and await and make your plan checks resolve promises. This makes your completePlan function a lot cleaner.

async completePlan() {
    try {
        const response1 = await this.checkFirstPlan();
        const response2 = await this.checkSecondPlan();
        
        this.completePlanConfirm();
    } catch (error) {
        console.error(error);
        throw error;
    }
}

checkFirstPlan(): Promise<any> {
    return new Promise((resolve, reject) => {
        this.planService.FirstCheck(this.plan.id).subscribe((data: any) => {
            if (!data.result) {
                throw new Error('Error 1')
            }
            resolve(data);
        }, (error: any) => {
          throw new Error(msg);
        }, () => { });
      });    
}

checkSecondPlan(): Promise<any> {
    return new Promise((resolve, reject) => {
        this.planService.SecondCheck(this.plan.id).subscribe((data: any) => {
            if (!data.result) {
                throw new Error('Error 2')
            }
            resolve(data);
        }, (error: any) => {
          throw new Error(msg);
        }, () => { });
      });    
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.