在 ES6 中扩展 Promise [英] Extending Promises in ES6

查看:19
本文介绍了在 ES6 中扩展 Promise的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试扩展 Promise:

I am trying to extend Promise:

class PersistedPromise extends Promise { }

然后在派生类上调用静态的resolve,直接创建一个resolved promise:

Then call the static resolve on the derived class to directly create a resolved promise:

PersistedPromise.resolve(1)

在 traceur 中,这会产生:

In traceur, this yields:

ModuleEvaluationError: #<PersistedPromise> is not a promise
    at new PersistedPromise (~rtm/gen/promise.js:6:57)
    at Function.resolve (native)

在 Babel 中(以 babel-node --experimental promise.js 运行)结果:

In Babel (run as babel-node --experimental promise.js) it results in:

    Promise.apply(this, arguments);
            ^
TypeError: [object Object] is not a promise
    at new PersistedPromise (~rtm/gen/promise.js:1:23)
    at Function.resolve (native)
    ...

我依赖于此:

Promise 的所有静态方法都支持子类化:它们通过接收器创建新实例(想想:new this(...))并通过它访问其他静态方法(this.resolve(...) 与 Promise.resolve(...)).

All static methods of Promise support subclassing: they create new instances via their receiver (think: new this(...)) and also access other static methods via it (this.resolve(...) versus Promise.resolve(...)).

来自 http://www.2ality.com/2014/10/es6-promises-api.html.

似乎节点在诸如 Promise.resolve.call(this, val) 之类的调用中检查 this 是否为 Promise,而不是(正确?)Promise 或其派生类(v0.12.0).

It appears that node checks the this on calls such as Promise.resolve.call(this, val) for being a Promise, rather than (correctly?) Promise or a derived class thereof (v0.12.0).

以上是否不再有效,或者没有纳入规范,或者只是没有被 traceur 和/或节点实现?

Is the above no longer operative, or did not make into the spec, or just not implemented by traceur and/or node?

推荐答案

以上是否不再有效,或者没有纳入规范,或者只是没有被 traceur 和/或节点实现?

Is the above no longer operative, or did not make into the spec, or just not implemented by traceur and/or node?

规范中的 ES6 承诺支持子类化.也就是说,您最终将能够像刚才那样对 promise 进行子类化.这是设计使然.

ES6 promises in the spec support subclassing. That is, you will eventually be able to subclass promises the way you just did. This is by design.

也就是说,目前没有任何浏览器在这方面正确遵循该规范 - 据我所知,只有 ES6-promise shim、Babel(core-js)和 RSVP 遵循 ES6 语义正确地进行子类化.浏览器的支持最终会到来,但还没有.抱紧.

That said, none of the browsers currently follow that spec correctly in this regard - as far as I know only the ES6-promise shim, Babel (core-js) and RSVP follow ES6 semantics with regards to subclassing correctly. Support in browsers is eventually coming but it's not there yet. Hold tight.

这是一个当前支持的实现列表.

这篇关于在 ES6 中扩展 Promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆