Promise finally

Raul-Sebastian Mihăilă raul.mihaila at gmail.com
Mon Feb 26 07:23:34 UTC 2018


This is an illustration of the current `Promise.prototype.finally`
deficiency. In this example, the `incr` method does 2 things. It increases
`count` by 1. And increases `methodCallsCount` by 1. At a later point in
time, it was decided to add an `incr3` method that did the same, but
increase `count` by 3, not by 1. There are two approaches illustrated, the
good counter and the bad counter. `Promise.prototype.finally` is currently
the bad counter. The good counter's `incr3` does exactly what it was
supposed to do, namely increases `count` by 3 and increases
`methodCallsCount` by 1. The bad counter's `incr3` calls `incr` 3 times in
order to increase `count` by 1 three times, thinking that it's equivalent.
The problem is that `incr` wasn't just increasing `count` by 1. It did more
than that. Therefore `incr3` is not expressible in terms of `incr`.
Similarly, `Promise.prototype.finally` shouldn't call
`Promise.prototype.then`, because, conceptually, it's definition doesn't
say that it must incur 2 extra ticks.

It's possible that library and framework authors will avoid using `finally`
for efficiency. The meeting notes don't illustrate that TC39 considered
this nuance seriously. Is it possible for TC39 to reconsider this matter?

```js
class GoodCounter {
  constructor() {
    this.count = 0;
    this.methodCallsCount = 0;
  }

  incr() {
    this.count += 1;
    this.methodCallsCount += 1;
  }

  incr3() {
    this.count += 3;
    this.methodCallsCount += 1;
  }
}

class BadCounter {
  constructor() {
    this.count = 0;
    this.methodCallsCount = 0;
  }

  incr() {
    this.count += 1;
    this.methodCallsCount += 1;
  }

  incr3() {
    this.incr();
    this.incr();
    this.incr();
  }
}

const c1 = new GoodCounter();

c1.incr();

c1.count; // 1
c1.methodCallsCount; // 1

c1.incr3();

c1.count; // 4
c1.methodCallsCount; // 2

const c2 = new BadCounter();

c2.incr();

c2.count; // 1
c2.methodCallsCount; // 1

c2.incr3();

c2.count; // 4
c2.methodCallsCount; // 4
```
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20180226/908ce9b7/attachment-0001.html>


More information about the es-discuss mailing list