Home > OS >  How to call async function inside Observable method sequentially?
How to call async function inside Observable method sequentially?

Time:07-16

I have the following method:

  public classMethod(
    payload: Payload,
  ): Observable<Result> {
    const { targetProp } = payload;
    let target;

    return this.secondClass.secondClassMethod({ targetProp }).pipe(
      delayWhen(() =>
        // some other actions
      ),
    );
  }

It is critical to set this target value before calling this.secondClass.secondClassMethod.

Is it possible to call regular async method like this:

  public classMethod(
    req: classMethodRequest,
  ): Observable<classMethodResponse> {
    const { targetProp } = req;
    let target;

    /**
    **  Calling async method here to set ```target```
    ** like 
    ** target = await someAsyncMethod(targetProp)
    **/

    return this.secondClass.secondClassMethod({ targetProp }).pipe(
      delayWhen(() =>
      ),
      
    );
  }

In other words, I would like to invoke method classMethod so, that classMethod will set target variable within it and then it will be possible to use target in the returning construction

return this.secondClass.secondClassMethod({ targetProp }).pipe(
      delayWhen(() =>
      ),
    );

I've tried to cover async method in:

 from(
      (async () => {
        target = await this.someAsyncMethod.setTarget(targetProp);
      })(),
    );

BUT I was told that this cover will invoke in parallel with

return this.secondClass.secondClassMethod({ targetProp }).pipe(
      delayWhen(() =>
      ),
    );

parallel is not an option here :(

CodePudding user response:

You can convert the promise to an observable using from and use switchMap

return from(this.someAsyncMethod.setTarget(targetProp)).pipe(
  switchMap(target => this.secondClass.secondClassMethod({ targetProp }),
  delayWhen(() => ... ),
);
  • Related