我在控制器中有一个@Get()方法。我得到了响应,但是在响应成功之后,我想在延迟几毫秒后调用异步方法。
我使用的是中间件,但响应似乎在异步方法中指定的时间内挂起。
如何及时解决响应问题,在延迟之后从自定义服务调用自定义方法?
下面是使用的示例代码:
@Controller()
export class CustomController {
@Get("custom-controller-route")
getCustomValue(@Res() response: Response) {
return response.status(200).send({
value: 1
})
}
}中间件代码如下:
@Injectable()
export class CustomMiddleware implements NestMiddleware {
constructor(private readonly customService: CustomService) {}
use(req: any, res: any, next: () => void) {
let send = res.send
res.send = async (customResponse: CustomResponse) => {
const { value } = customResponse
await customService.customMethod(value, 5000) // Delay of 5 seconds
res.send = send
return res.send(exchangeRateResponse)
}
next()
}
}CustomService有下一个代码:
@Injectable()
export class CustomService {
async customMethod(value: any, delay) {
await firstValueFrom(
timer(delay).pipe(
tap(() => {
// Here is the logic that needs to be run in the delay time after the response is finished
console.log(`Custom Service - custom method called with: ${value} after: ${delay} milliseconds.`)
})
)
)
}
}发布于 2022-05-23 20:00:27
我可以这样做,而不是在Controller方法中返回响应,我只使用特定的响应调用res.status(200).send({}),然后用延迟调用特定的方法调用。
@Controller()
export class CustomController {
@Get("custom-controller-route")
getCustomValue(@Res() response: Response) {
response.status(200).send({ value: 1 })
// Call the delayed Service method
}
}欢迎其他更好的选择。
https://stackoverflow.com/questions/72352905
复制相似问题