promises-aplus / promises-spec

An open standard for sound, interoperable JavaScript promises—by implementers, for implementers.
https://promisesaplus.com/
Creative Commons Zero v1.0 Universal
1.84k stars 171 forks source link

Adopting state without .then() #270

Open paulstelian97 opened 5 years ago

paulstelian97 commented 5 years ago

I have made my own promises library which attempts to expose an API similar to Javascript's own promises. However there is one thing which your spec doesn't provide (or I am confused): if the original promise (the one made with e.g. the constructor) will resolve with a thenable, what should the first .then() callback give?

const promise1 = new MyPromise(resolve => resolve(5));
const promise2 = new MyPromise(resolve => resolve(promise1));
const final = new MyPromise(resolve => resolve(promise2)).then(val => console.log(val))
const final2 = new MyPromise(resolve => resolve(promise2)).then().then(val => console.log(val))

What should be displayed for the first final promise? Should it be 5 or one of promise1 or promise2? The second one will display 5 anyway.

bergus commented 5 years ago

The Promises/A+ then method does not support fulfilling with thenables (when returning them from the then callback`). This spec does not say anything about the constructor, it doesn't answer your question.

You can do either. You should decide whether the callback in your constructor is a resolve or a fulfill. You got three choices:

paulstelian97 commented 5 years ago

I'm pretty sure promise1 should resolve to the value 5, but otherwise thank you. I have chosen to call then() in the constructor (without that final would resolve to promise2 in my implementation)

Note that it passes all tests in the tests repo either way (it's inspired by RWPromises)