Michael Plakhov Michael Plakhov - 9 months ago 50
Javascript Question

What is the reason to allow multiple resolve/reject in ES6 Promise

I found that is possible (in ES6 promises, while Promise object is created) to use multiple resolve/reject which will affect PromiseStatus only once but not affect execution flow.

var p = new Promise(function(resolve, reject) {
console.log('Resolve 1');
}, 50);
console.log('Resolve 2');
}, 100);

console.log('Status #1:', p);
}, 10);
console.log('Status #2:', p);
}, 60);
console.log('Status #3:', p);
}, 110);

console.log('Value after:', x)

functions first resolve/reject will affect execution flow.
So my question is - why it works like this (feature/bug)?

P.S. My env is Node 4.1

P.P.S. My output:

Status #1: Promise { <pending> }
Resolve 1
Value after: 1
Status #2: Promise { 1 }
Resolve 2
Status #3: Promise { 1 }


Well, I want to talk about the why. Promises are proxies for single values so running handlers a second time or changing the value doesn't make sense. You can't change the number 5 to be the number 3 for instance.

Let's talk about what alternatives we have for resolve being called a second time. Let's say we didn't want to allow it - how would we signal that?

Normally, we'd throw - the problem is - it would be caught nowhere since throws in the promise constructor get converted to rejections. .catch handlers would not run because the promise already resolved.

So we can't really throw as that'd mean an exception you can't handle (a very bad place to be). We can't run handlers twice (that would break the model). So our only choice left is to allow it.