'PromiseLike <any>类型中不存在属性'catch'

时间:2018-01-27 00:13:16

标签: javascript firebase firebase-realtime-database angularfire2

我有以下代码:

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

我在'catch'上收到以下错误:

[ts] Property 'catch' does not exist on type 'PromiseLike<any>'.

好像是一个AngularFire2错误?

1 个答案:

答案 0 :(得分:3)

报告错误是因为typescript中的PromiseLike接口缺少catch方法。这与“可以”作为具有then方法的对象的定义一致。

interface PromiseLike {
    /**
     * Attaches callbacks for the resolution and/or rejection of the Promise.
     * @param onfulfilled The callback to execute when the Promise is resolved.
     * @param onrejected The callback to execute when the Promise is rejected.
     * @returns A Promise for the completion of which ever callback is executed.
     */
    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+ spec未提及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));

或将Promise.prototype.catch的代码扩展为then来电:

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