2

I have been trying to make a event-emitter using ES6 promises, but when the saved response is called the second time it doesn't return anything.

var z;
function test(){
    return new Promise((resolve) => {
        z = resolve;
    });
}

test().then(()=> console.log('aaaaaaaaaaaaaaaaaaaaaaaa') )

console.log(z) // ƒ () { [native code] }
z(); // aaaaaaaaaaaaaaaaaaaaaaaa
z(); // <empty>
Alex C
  • 516
  • 7
  • 15

1 Answers1

2

when the saved response is called the second time

Promises are only settled once. Once a promise is settled (resolved or rejected), that's it; its state never changes again. Subsequent calls to the resolve and reject functions passed to the promise executor are ignored. (Some would prefer that they throw, but they don't.)

If you want an event emitter, a promise is just the wrong technology, since events can happen more than once.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875