Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
394 views
in Technique[技术] by (71.8m points)

ecmascript 6 - Extending Promises in ES6

I am trying to extend Promise:

class PersistedPromise extends Promise { }

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

PersistedPromise.resolve(1)

In traceur, this yields:

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

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)
    ...

I was depending on this:

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(...)).

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

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).

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.

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.

Here is a list of currently supporting implementations.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...