Path: blob/trunk/third_party/closure/goog/result/simpleresult.js
2868 views
// Copyright 2012 The Closure Library Authors. All Rights Reserved.1//2// Licensed under the Apache License, Version 2.0 (the "License");3// you may not use this file except in compliance with the License.4// You may obtain a copy of the License at5//6// http://www.apache.org/licenses/LICENSE-2.07//8// Unless required by applicable law or agreed to in writing, software9// distributed under the License is distributed on an "AS-IS" BASIS,10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11// See the License for the specific language governing permissions and12// limitations under the License.1314/**15* @fileoverview A SimpleResult object that implements goog.result.Result.16* See below for a more detailed description.17*/1819goog.provide('goog.result.SimpleResult');20goog.provide('goog.result.SimpleResult.StateError');2122goog.require('goog.Promise');23goog.require('goog.Thenable');24goog.require('goog.debug.Error');25goog.require('goog.result.Result');26272829/**30* A SimpleResult object is a basic implementation of the31* goog.result.Result interface. This could be subclassed(e.g. XHRResult)32* or instantiated and returned by another class as a form of result. The caller33* receiving the result could then attach handlers to be called when the result34* is resolved(success or error).35*36* @constructor37* @implements {goog.result.Result}38* @deprecated Use {@link goog.Promise} instead - http://go/promisemigration39*/40goog.result.SimpleResult = function() {41/**42* The current state of this Result.43* @type {goog.result.Result.State}44* @private45*/46this.state_ = goog.result.Result.State.PENDING;4748/**49* The list of handlers to call when this Result is resolved.50* @type {!Array<!goog.result.SimpleResult.HandlerEntry_>}51* @private52*/53this.handlers_ = [];5455// The value_ and error_ properties are initialized in the constructor to56// ensure that all SimpleResult instances share the same hidden class in57// modern JavaScript engines.5859/**60* The 'value' of this Result.61* @type {*}62* @private63*/64this.value_ = undefined;6566/**67* The error slug for this Result.68* @type {*}69* @private70*/71this.error_ = undefined;72};73goog.Thenable.addImplementation(goog.result.SimpleResult);747576/**77* A waiting handler entry.78* @typedef {{79* callback: !function(goog.result.SimpleResult),80* scope: Object81* }}82* @private83*/84goog.result.SimpleResult.HandlerEntry_;85868788/**89* Error thrown if there is an attempt to set the value or error for this result90* more than once.91*92* @constructor93* @extends {goog.debug.Error}94* @final95* @deprecated Use {@link goog.Promise} instead - http://go/promisemigration96*/97goog.result.SimpleResult.StateError = function() {98goog.result.SimpleResult.StateError.base(99this, 'constructor', 'Multiple attempts to set the state of this Result');100};101goog.inherits(goog.result.SimpleResult.StateError, goog.debug.Error);102103104/** @override */105goog.result.SimpleResult.prototype.getState = function() {106return this.state_;107};108109110/** @override */111goog.result.SimpleResult.prototype.getValue = function() {112return this.value_;113};114115116/** @override */117goog.result.SimpleResult.prototype.getError = function() {118return this.error_;119};120121122/**123* Attaches handlers to be called when the value of this Result is available.124*125* @param {function(this:T, !goog.result.SimpleResult)} handler The function126* called when the value is available. The function is passed the Result127* object as the only argument.128* @param {T=} opt_scope Optional scope for the handler.129* @template T130* @override131*/132goog.result.SimpleResult.prototype.wait = function(handler, opt_scope) {133if (this.isPending_()) {134this.handlers_.push({callback: handler, scope: opt_scope || null});135} else {136handler.call(opt_scope, this);137}138};139140141/**142* Sets the value of this Result, changing the state.143*144* @param {*} value The value to set for this Result.145*/146goog.result.SimpleResult.prototype.setValue = function(value) {147if (this.isPending_()) {148this.value_ = value;149this.state_ = goog.result.Result.State.SUCCESS;150this.callHandlers_();151} else if (!this.isCanceled()) {152// setValue is a no-op if this Result has been canceled.153throw new goog.result.SimpleResult.StateError();154}155};156157158/**159* Sets the Result to be an error Result.160*161* @param {*=} opt_error Optional error slug to set for this Result.162*/163goog.result.SimpleResult.prototype.setError = function(opt_error) {164if (this.isPending_()) {165this.error_ = opt_error;166this.state_ = goog.result.Result.State.ERROR;167this.callHandlers_();168} else if (!this.isCanceled()) {169// setError is a no-op if this Result has been canceled.170throw new goog.result.SimpleResult.StateError();171}172};173174175/**176* Calls the handlers registered for this Result.177*178* @private179*/180goog.result.SimpleResult.prototype.callHandlers_ = function() {181var handlers = this.handlers_;182this.handlers_ = [];183for (var n = 0; n < handlers.length; n++) {184var handlerEntry = handlers[n];185handlerEntry.callback.call(handlerEntry.scope, this);186}187};188189190/**191* @return {boolean} Whether the Result is pending.192* @private193*/194goog.result.SimpleResult.prototype.isPending_ = function() {195return this.state_ == goog.result.Result.State.PENDING;196};197198199/**200* Cancels the Result.201*202* @return {boolean} Whether the result was canceled. It will not be canceled if203* the result was already canceled or has already resolved.204* @override205*/206goog.result.SimpleResult.prototype.cancel = function() {207// cancel is a no-op if the result has been resolved.208if (this.isPending_()) {209this.setError(new goog.result.Result.CancelError());210return true;211}212return false;213};214215216/** @override */217goog.result.SimpleResult.prototype.isCanceled = function() {218return this.state_ == goog.result.Result.State.ERROR &&219this.error_ instanceof goog.result.Result.CancelError;220};221222223/** @override */224goog.result.SimpleResult.prototype.then = function(225opt_onFulfilled, opt_onRejected, opt_context) {226var resolve, reject;227// Copy the resolvers to outer scope, so that they are available228// when the callback to wait() fires (which may be synchronous).229var promise = new goog.Promise(function(res, rej) {230resolve = res;231reject = rej;232});233this.wait(function(result) {234if (result.isCanceled()) {235promise.cancel();236} else if (result.getState() == goog.result.Result.State.SUCCESS) {237resolve(result.getValue());238} else if (result.getState() == goog.result.Result.State.ERROR) {239reject(result.getError());240}241});242return promise.then(opt_onFulfilled, opt_onRejected, opt_context);243};244245246/**247* Creates a SimpleResult that fires when the given promise resolves.248* Use only during migration to Promises.249* @param {!goog.Promise<?>} promise250* @return {!goog.result.Result}251*/252goog.result.SimpleResult.fromPromise = function(promise) {253var result = new goog.result.SimpleResult();254promise.then(result.setValue, result.setError, result);255return result;256};257258259