【问题标题】:How to call HttpException in setTimeout, when i wait promise a long time?当我等待承诺很长时间时,如何在 setTimeout 中调用 HttpException?
【发布时间】:2022-01-18 07:39:43
【问题描述】:

我从不同的服务器获取产品,我想在等待很长时间时返回异常。 我为此创建了 setTimeout,但它停止了服务器并且没有返回错误。

如何解决?

      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);
          }
        });
      });

【问题讨论】:

  • 为什么要触发异常?我会在x 秒后reject(new Error("<meaningful message")) Promise()new Promise((resolve, reject) => { setTimeout(() => reject(new Error("Ups")), 5000); /*...*/ }
  • @Andreas 语法略有改进:setTimeout(reject, 5000, new Error('Ups')).
  • @Andreas 套接字服务器可能会在下一个响应中返回所需的数据,但我需要修复此响应的超时时间。
  • 维护 isTimedOut 并将其设置在 setTimeout 中。设置后将其传递给需要拒绝的其他操作。

标签: javascript node.js exception nestjs


【解决方案1】:

用户删除了他的答案,我已经修复了。

      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
      ])

这是工作。

【讨论】:

  • 不错... !!!使用承诺...
  • 是的,我来晚了,你需要的是 race 而不是 any
猜你喜欢
  • 2021-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多