简体   繁体   中英

Does my Promise implementation agree with specifications?

I am trying to create a Typescript promise implementation (actually a polyfill) that agrees with current specifications (I used these http://promises-aplus.github.io/promises-spec/ ).

It should be done, code is here https://gist.github.com/ilmattodel93/dbefa9eb86715f76e10e , but I can't understand the 2.2.7 subpoints of the specs. Only race and all static methods should be missing.

Please someone can explain me the 2.2.7 subpoints and tell me if I have implemented them correctly?

Thanks for attention and time, Mattia.

Let's let the code do the talking. Lets say we have a promise called promise1 . According to the spec:

From Spec

then must return a promise

self explainatory:

promise2 = promise1.then(onFulfilled, onRejected);

From Spec

If either onFulfilled or onRejected returns a value x, run the Promise Resolution Procedure [[Resolve]](promise2, x).

If we have

promise2 = promise1.then(()=>123,()=>123);

Then you can do

promise2.then((x)=> /* x should be 123 */, (x)=> /* will not be called */);

From Spec

If either onFulfilled or onRejected throws an exception e, promise2 must be rejected with e as the reason.

If we have

promise2 = promise1.then(()=> { throw new Error('message'); }, ()=> { throw new Error('message'); });

Then you can do

promise2.then((x)=> /* should not be called */, (x)=> /* x will be equal to "new Error('message')" */);

From Spec

If onFulfilled is not a function and promise1 is fulfilled, promise2 must be fulfilled with the same value.

if we have

promise1 = new Promise(function(resolve,reject) { resolve(123) });
promise2 = promise1.then(null,null);

Then we can do

promise2.then((x)=> /* x should be 123 */, (x)=> /* should not be called */);

From Spec

If onRejected is not a function and promise1 is rejected, promise2 must be rejected with the same reason.

if we have

promise1 = new Promise(function(resolve,reject) { reject(123) });
promise2 = promise1.then(null,null);

Then we can do

promise2.then((x)=> /* should not be called */, (x)=> /* x should be 123 */);

To verify that you implementation write tests as shown. I recommend using Mocha with Chai.

You can also check your TypeScript definition to compatibility with spec's promises/A+ definition. Here is the TypeScript code for spec's promise: DefinitelyTyped on GitHub .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM