[英]How to use async/await inside effects angular NgRx?
I'm running this code:我正在运行这段代码:
public customCommand$ = createEffect(() =>
this.actions$.pipe(
ofType(appActions.customCommand),
tap(action => console.log(action)),
switchMap( (action) => {
const { commandInput } = action;
const commandOutput = this.shellExecutor.executeCommand(commandInput);
return this.generalApiService
.sendCustomCommandResult(commandInput, commandOutput).pipe(
map((res) => appActions.customCommandSuccess({ commandOutput: res })),
catchError(() => of(appActions.checkHebrewLocaleError())),
);
}),
catchError(() => of(appActions.customCommandError())),
),
);
and I need to await for commandOutput answer, the problem that commandOutput return a Promise and i've try to use async/await and i'm getting an error.我需要等待commandOutput的答案, commandOutput返回 Promise 的问题,我尝试使用 async/await,但出现错误。 attaching a screenshot:
附上截图:
I've found this solution, just wrap with switchMap the action that I need to use with async/await answer and than pass the result to another switchMap, not sure that is the best way but it works.我找到了这个解决方案,只需用 switchMap 包装我需要与 async/await 答案一起使用的操作,然后将结果传递给另一个 switchMap,不确定这是最好的方法,但它可以工作。
public customCommand$ = createEffect(() =>
this.actions$.pipe(
ofType(appActions.customCommand),
switchMap(async (action) => {
const { commandInput } = action;
const commandOutput = await this.shellExecutor.executeCommand(commandInput);
return { commandInput, commandOutput};
}),
switchMap((commandState: CommandState) => {
const {commandInput, commandOutput} = commandState;
return this.generalApiService
.sendCustomCommandResult(commandInput, commandOutput).pipe(
switchMap((res) => {
return of(appActions.customCommandSuccess({ commandOutput: res }));
}),
catchError(() => of(appActions.customCommandError())),
);
}),
catchError(() => of(appActions.customCommandError())),
),
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.