Should I change the internal state of the value that has been promised and already resolved?

Code Example (Volatility)

.factory('objSingleton', function ($q) {
  var o = {a: 1}

  setTimeout(function () {
    o.a = 2
  }, 1000)

  return $q.when(o)
})

An alternative would be (immutability)

.factory('objFactory', function ($q) {
  var promise = $q.when({a: 1})

  setTimeout(function () {
    promise = $q.when({a: 2})
  }, 1000)

  return function () {
    return promise
  }
})

Question

I would like to hear the pros and cons to help me decide how to accept or refrain from processing promises (in the APIs that create + return them) that are deeply immutable.

Note. The code sample uses an AngularJS style dependency injector, but the question and answer applies to any JS environment that uses promises.

+4
source share
3 answers

Promises should not play any role in making this decision.

, , . - .

, , . Mutable state . . , Angular Misko Havery .

, : , . . , , " ".

+3

. . angular, , , angular . , angular, .

, $watch . - .

, .

+2

.

Promises , . , , , . , "".

. , Object.freeze .

, . , , , , .

In my personal vision, angular does it too liberally, but the automatic distribution of such mutations is their design.

+1
source

Source: https://habr.com/ru/post/1538544/


All Articles