Search code examples
angularrxjsngrx

Can I use async/await inside an RxJs switchMap being used in an NgRx effect


I am setting up new Effect modules in my Angular NgRx enabled application.

When I have a view opened, I want to make quite a few requests. As there are a number of requests, I wanted to put these into their own method and have these dispatch the success or failed actions. The API for these requests are all async methods (they return a promise)

I have the following

    public viewOpened$ = createEffect(() => this.actions$.pipe(
        ofType(myActions.viewOpened),

        // Use a switchMap to cancel any ongoing subscriptions if request new comes in
        switchMap(_ => {    
                (async () => {
                    this.logger.info('view Opened');
                    const p1 = this.request1();
                    const p2 = this.request2();

                    // await so switchMap can handle any race conditions
                    await Promise.all([p1, p2]);
                });     

            // Need to return an observable (but this is not used)
            return of({})
        })    
    ), { dispatch: false });
    

I am using a switchMap hoping this will look after any "race conditions" for me, i.e., if the view is quickly opened, closed, and then opened again, the switchMap will cancel any previous uncompleted requests.

But what I am finding above is the code inside the async is never called.

Is there a reason my async code is not being called and is what I am trying to do above possible?


Solution

  • You're wrapping the async invocation with parenthesis at this juncture you must make it an immediately invoked async function expression. Basically you're missing some parenthesis that execute the async function after wrapping the async function expression in parenthesis. I think it should be similar to: (async () => {...})()