simpleresult.js 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. // Copyright 2012 The Closure Library Authors. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS-IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. /**
  15. * @fileoverview A SimpleResult object that implements goog.result.Result.
  16. * See below for a more detailed description.
  17. */
  18. goog.provide('goog.result.SimpleResult');
  19. goog.provide('goog.result.SimpleResult.StateError');
  20. goog.require('goog.Promise');
  21. goog.require('goog.Thenable');
  22. goog.require('goog.debug.Error');
  23. goog.require('goog.result.Result');
  24. /**
  25. * A SimpleResult object is a basic implementation of the
  26. * goog.result.Result interface. This could be subclassed(e.g. XHRResult)
  27. * or instantiated and returned by another class as a form of result. The caller
  28. * receiving the result could then attach handlers to be called when the result
  29. * is resolved(success or error).
  30. *
  31. * @constructor
  32. * @implements {goog.result.Result}
  33. * @deprecated Use {@link goog.Promise} instead - http://go/promisemigration
  34. */
  35. goog.result.SimpleResult = function() {
  36. /**
  37. * The current state of this Result.
  38. * @type {goog.result.Result.State}
  39. * @private
  40. */
  41. this.state_ = goog.result.Result.State.PENDING;
  42. /**
  43. * The list of handlers to call when this Result is resolved.
  44. * @type {!Array<!goog.result.SimpleResult.HandlerEntry_>}
  45. * @private
  46. */
  47. this.handlers_ = [];
  48. // The value_ and error_ properties are initialized in the constructor to
  49. // ensure that all SimpleResult instances share the same hidden class in
  50. // modern JavaScript engines.
  51. /**
  52. * The 'value' of this Result.
  53. * @type {*}
  54. * @private
  55. */
  56. this.value_ = undefined;
  57. /**
  58. * The error slug for this Result.
  59. * @type {*}
  60. * @private
  61. */
  62. this.error_ = undefined;
  63. };
  64. goog.Thenable.addImplementation(goog.result.SimpleResult);
  65. /**
  66. * A waiting handler entry.
  67. * @typedef {{
  68. * callback: !function(goog.result.SimpleResult),
  69. * scope: Object
  70. * }}
  71. * @private
  72. */
  73. goog.result.SimpleResult.HandlerEntry_;
  74. /**
  75. * Error thrown if there is an attempt to set the value or error for this result
  76. * more than once.
  77. *
  78. * @constructor
  79. * @extends {goog.debug.Error}
  80. * @final
  81. * @deprecated Use {@link goog.Promise} instead - http://go/promisemigration
  82. */
  83. goog.result.SimpleResult.StateError = function() {
  84. goog.result.SimpleResult.StateError.base(
  85. this, 'constructor', 'Multiple attempts to set the state of this Result');
  86. };
  87. goog.inherits(goog.result.SimpleResult.StateError, goog.debug.Error);
  88. /** @override */
  89. goog.result.SimpleResult.prototype.getState = function() {
  90. return this.state_;
  91. };
  92. /** @override */
  93. goog.result.SimpleResult.prototype.getValue = function() {
  94. return this.value_;
  95. };
  96. /** @override */
  97. goog.result.SimpleResult.prototype.getError = function() {
  98. return this.error_;
  99. };
  100. /**
  101. * Attaches handlers to be called when the value of this Result is available.
  102. *
  103. * @param {function(this:T, !goog.result.SimpleResult)} handler The function
  104. * called when the value is available. The function is passed the Result
  105. * object as the only argument.
  106. * @param {T=} opt_scope Optional scope for the handler.
  107. * @template T
  108. * @override
  109. */
  110. goog.result.SimpleResult.prototype.wait = function(handler, opt_scope) {
  111. if (this.isPending_()) {
  112. this.handlers_.push({callback: handler, scope: opt_scope || null});
  113. } else {
  114. handler.call(opt_scope, this);
  115. }
  116. };
  117. /**
  118. * Sets the value of this Result, changing the state.
  119. *
  120. * @param {*} value The value to set for this Result.
  121. */
  122. goog.result.SimpleResult.prototype.setValue = function(value) {
  123. if (this.isPending_()) {
  124. this.value_ = value;
  125. this.state_ = goog.result.Result.State.SUCCESS;
  126. this.callHandlers_();
  127. } else if (!this.isCanceled()) {
  128. // setValue is a no-op if this Result has been canceled.
  129. throw new goog.result.SimpleResult.StateError();
  130. }
  131. };
  132. /**
  133. * Sets the Result to be an error Result.
  134. *
  135. * @param {*=} opt_error Optional error slug to set for this Result.
  136. */
  137. goog.result.SimpleResult.prototype.setError = function(opt_error) {
  138. if (this.isPending_()) {
  139. this.error_ = opt_error;
  140. this.state_ = goog.result.Result.State.ERROR;
  141. this.callHandlers_();
  142. } else if (!this.isCanceled()) {
  143. // setError is a no-op if this Result has been canceled.
  144. throw new goog.result.SimpleResult.StateError();
  145. }
  146. };
  147. /**
  148. * Calls the handlers registered for this Result.
  149. *
  150. * @private
  151. */
  152. goog.result.SimpleResult.prototype.callHandlers_ = function() {
  153. var handlers = this.handlers_;
  154. this.handlers_ = [];
  155. for (var n = 0; n < handlers.length; n++) {
  156. var handlerEntry = handlers[n];
  157. handlerEntry.callback.call(handlerEntry.scope, this);
  158. }
  159. };
  160. /**
  161. * @return {boolean} Whether the Result is pending.
  162. * @private
  163. */
  164. goog.result.SimpleResult.prototype.isPending_ = function() {
  165. return this.state_ == goog.result.Result.State.PENDING;
  166. };
  167. /**
  168. * Cancels the Result.
  169. *
  170. * @return {boolean} Whether the result was canceled. It will not be canceled if
  171. * the result was already canceled or has already resolved.
  172. * @override
  173. */
  174. goog.result.SimpleResult.prototype.cancel = function() {
  175. // cancel is a no-op if the result has been resolved.
  176. if (this.isPending_()) {
  177. this.setError(new goog.result.Result.CancelError());
  178. return true;
  179. }
  180. return false;
  181. };
  182. /** @override */
  183. goog.result.SimpleResult.prototype.isCanceled = function() {
  184. return this.state_ == goog.result.Result.State.ERROR &&
  185. this.error_ instanceof goog.result.Result.CancelError;
  186. };
  187. /** @override */
  188. goog.result.SimpleResult.prototype.then = function(
  189. opt_onFulfilled, opt_onRejected, opt_context) {
  190. var resolve, reject;
  191. // Copy the resolvers to outer scope, so that they are available
  192. // when the callback to wait() fires (which may be synchronous).
  193. var promise = new goog.Promise(function(res, rej) {
  194. resolve = res;
  195. reject = rej;
  196. });
  197. this.wait(function(result) {
  198. if (result.isCanceled()) {
  199. promise.cancel();
  200. } else if (result.getState() == goog.result.Result.State.SUCCESS) {
  201. resolve(result.getValue());
  202. } else if (result.getState() == goog.result.Result.State.ERROR) {
  203. reject(result.getError());
  204. }
  205. });
  206. return promise.then(opt_onFulfilled, opt_onRejected, opt_context);
  207. };
  208. /**
  209. * Creates a SimpleResult that fires when the given promise resolves.
  210. * Use only during migration to Promises.
  211. * @param {!goog.Promise<?>} promise
  212. * @return {!goog.result.Result}
  213. */
  214. goog.result.SimpleResult.fromPromise = function(promise) {
  215. var result = new goog.result.SimpleResult();
  216. promise.then(result.setValue, result.setError, result);
  217. return result;
  218. };