I get products from different servers, I want return exception, when wait a long time. I have created setTimeout for this, but it stoped server and didn't return error.
How to fix it?
const server = 23;
const productsTimeout = setTimeout(() => { throw new HttpException('Problem', HttpStatus.INTERNAL_SERVER_ERROR) }, 3000);
products = await new Promise((resolve, reject) => {
this.socketClientCabinet.on('products_get', async ({ server, products }) => {
if (server === serverID) {
const {
productsSymbols,
} = this.productsTransform(products);
clearTimeout(productsTimeout);
resolve(productsSymbols);
}
});
});
User delete his answer, I have fixed it.
let productsTimeout;
const timeoutPromise = new Promise((res, rej) => {
instrumentsTimeout = setTimeout(() => rej(new HttpException('problem', 500)), 1000, )
})
const productsPromise = new Promise((resolve, reject) => {
this.socketClientCabinet.on('products_get', async ({ server, products }) => {
if (server === serverID) {
const {
productsSymbols,
} = this.productsTransform(products);
clearTimeout(productsTimeout);
resolve(productsSymbols);
}
});
});
const products = await Promise.race([
timeoutPromise,
productsPromise
])
It is work.