网站搜索

javascript - 故意不返回 Bluebird Promise


我有下面这段代码。想要调用可能会返回 Promise 的回调。将其解析。如果 Promise 失败,则记录它。调用者不应该知道这一切,并且应该在不等待 Promise 完成的情况下返回。这就是我不返回 Promise 的原因。这会导致以下错误:

(node:21146) Warning: a promise was created in a handler at internal/timers.js:456:21 but was not returned from it, see http  goo.gl/rRqMUw
    at Function.Promise.cast (bluebird/js/release/promise.js:225:13)

我已经阅读了文档,他们建议返回 null 来防止警告出现。然而,警告仍然弹出。另外,也不想全局禁用这个警告。

    private _trigger(cb : () => Resolvable<any>)
    {
        try
        {
            const res = cb();
            const prom = Promise.resolve(res);
            prom.catch(reason => {
                this.logger.error("ERROR: ", reason);
            })
        }
        catch(reason)
        {
            this.logger.error("ERROR: ", reason);
        }
        return null;
    }

答案#1

内部的 Promise 应该 解析 为 null 值以消除警告——这将告诉 Bluebird “Promise 没有被返回,但由于它解析为 null,它不包含有用的结果,因此这是故意的”;返回它不会给调用者提供有用的数据。你可以这样做:

const prom = Promise.resolve(res)
  .catch(reason => {
    this.logger.error("ERROR: ", reason);
  })
  .then(() => null);