用 node.js 原生 promises 替换 bluebird 中断 Promise.reject

Replacing bluebird with node.js native promises breaks Promise.reject

当我使用 bluebird promises 时,以下代码工作得很好:

import * as Promise from 'bluebird';

getAccount(id) {
    var account = find(accounts, ['id', id]);
    return account ?
        Promise.resolve(account) :
        Promise.reject(new NotFoundError());
}

NotFoundError定义如下:

export function NotFoundError(message = 'Not Found') {
    this.name = 'NotFoundError';
    this.message = message;
    this.stack = (new Error()).stack;
}
NotFoundError.prototype = Object.create(Error.prototype);
NotFoundError.prototype.constructor = NotFoundError;

但是,如果我在 getAccount() 中删除 bluebird 的导入并让 node.js 接管承诺,代码在 NotFoundError() 构造函数中失败,因为 this 不是定义。具体来说,构造函数被调用两次,一次从上面显示的 getAccount() 代码正确调用,第二次被 node.js 的 _tickCallback() 函数调用,其中 this 未定义:

NotFoundError (errors.js:13)
runMicrotasksCallback (internal/proces…ext_tick.js:58)
_combinedTickCallback (internal/proces…ext_tick.js:67)
_tickCallback (internal/proces…ext_tick.js:98)

为什么 node.js 第二次调用 NotFoundError() 构造函数而且那太不正确了!!!

请帮忙。

问题是由by this line引起的:

.catch(NotFoundError, function() { ... })

Native promises 没有将特定错误 class 传递给 catch 方法的选项,因此发生错误时会调用 NotFoundError (前面没有 new)因为它被认为是捕获处理程序。