首页 > 解决方案 > 故意不返回 Bluebird 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;
    }

标签: javascripttypescriptpromisebluebird

解决方案


内部 Promise 应该解析为一个值null以使警告静音 - 这将告诉 Bluebird“没有返回 Promise,但由于它解析为 null,它不包含有用的结果,所以这是故意的”;返回它不会给调用者有用的数据。您可以执行以下操作:

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

推荐阅读