类型“PromiseLike<any>”上不存在属性“catch”

fli*_*ode 1 javascript firebase firebase-realtime-database angularfire2

我有以下代码:

this.afDb.list('/demo').push({a: 'b'})
    .then(_ => console.log('works'))
    .catch(err => console.log('err: ', err));
Run Code Online (Sandbox Code Playgroud)

我在“捕获”上收到以下错误:

[ts] Property 'catch' does not exist on type 'PromiseLike<any>'.
Run Code Online (Sandbox Code Playgroud)

看起来像一个 AngularFire2 错误?

tra*_*r53 6

报错是因为PromiseLiketypescript中的接口缺少catch方法。这与将“thenable”定义为具有then方法。

接口 PromiseLike {
    /**
     * 附加回调以解决和/或拒绝 Promise。
     * @param onfulfilled Promise 解决时执行的回调。
     * @param onrejected Promise 被拒绝时执行的回调。
     * @returns 一个承诺完成哪个回调被执行。
     */
    then(onfulfilled?: ((value: T) => TResult1 | PromiseLike) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike) | undefined | null): PromiseLike;
}

是它在gitHub上的 lib.es2015.promise.d.ts 中的定义方式,从第 1291 行开始。(链接的 HTML 页面大小为 5.5MB - 可能需要一段时间。)

还要记住,A5+ 规范没有提到catch方法,并且 ES6 (ECMAScript 2015) 承诺提供catch一个Promise.prototype函数,该函数只then使用 的第一个参数catch作为第二个参数调用then

最简单的解决方案可能是使用两个参数then调用:

this.afDb.list('/demo').push({a: 'b'})
    .then(_ => console.log('works'),
          err => console.log('err: ', err));
Run Code Online (Sandbox Code Playgroud)

或扩展的代码Promise.prototype.catchthen呼叫:

this.afDb.list('/demo').push({a: 'b'})
    .then(_ => console.log('works'))
    .then( null, err => console.log('err: ', err)); // catch
Run Code Online (Sandbox Code Playgroud)