'use strict';
import _Global = require('../Core/_Global');
import _BaseCoreUtils = require('../Core/_BaseCoreUtils');
import _Base = require('../Core/_Base');
import _ErrorFromName = require('../Core/_ErrorFromName');
import _Events = require('../Core/_Events');
import _Trace = require('../Core/_Trace');
_Global.Debug && (_Global.Debug.setNonUserCodeExceptions = true);
//var ListenerType = _Base.Class.mix(_Base.Class.define(null, { /*empty*/ }, { supportedForProcessing: false }), _Events.eventMixin);
var promiseEventListeners = new _Events.EventListener();
// make sure there is a listeners collection so that we can do a more trivial check below
promiseEventListeners._listeners = {};
var errorET = "error";
var canceledName = "Canceled";
var tagWithStack = false;
var tag: any = {
promise: 0x01,
thenPromise: 0x02,
errorPromise: 0x04,
exceptionPromise: 0x08,
completePromise: 0x10,
};
tag.all = tag.promise | tag.thenPromise | tag.errorPromise | tag.exceptionPromise | tag.completePromise;
//
// Global error counter, for each error which enters the system we increment this once and then
// the error number travels with the error as it traverses the tree of potential handlers.
//
// When someone has registered to be told about errors (WinJS.Promise.callonerror) promises
// which are in error will get tagged with a ._errorId field. This tagged field is the
// contract by which nested promises with errors will be identified as chaining for the
// purposes of the callonerror semantics. If a nested promise in error is encountered without
// a ._errorId it will be assumed to be foreign and treated as an interop boundary and
// a new error id will be minted.
//
var error_number = 1;
//
// The state machine has a interesting hiccup in it with regards to notification, in order
// to flatten out notification and avoid recursion for synchronous completion we have an
// explicit set of *_notify states which are responsible for notifying their entire tree
// of children. They can do this because they know that immediate children are always
// ThenPromise instances and we can therefore reach into their state to access the
// _listeners collection.
//
// So, what happens is that a Promise will be fulfilled through the _completed or _error
// messages at which point it will enter a *_notify state and be responsible for to move
// its children into an (as appropriate) success or error state and also notify that child's
// listeners of the state transition, until leaf notes are reached.
//
export var state_created; // -> working
var state_working, // -> error | error_notify | success | success_notify | canceled | waiting
state_waiting, // -> error | error_notify | success | success_notify | waiting_canceled
state_waiting_canceled, // -> error | error_notify | success | success_notify | canceling
state_canceled, // -> error | error_notify | success | success_notify | canceling
state_canceling, // -> error_notify
state_success_notify, // -> success
state_success, // -> .
state_error_notify, // -> error
state_error; // -> .
// Noop function, used in the various states to indicate that they don't support a given
// message. Named with the somewhat cute name '_' because it reads really well in the states.
function _() { }
// Initial state
//
state_created = {
name: "created",
enter: function(promise) {
promise._setState(state_working);
},
cancel: _,
done: _,
then: _,
_completed: _,
_error: _,
_notify: _,
_progress: _,
_setCompleteValue: _,
_setErrorValue: _
};
// Ready state, waiting for a message (completed/error/progress), able to be canceled
//
state_working = {
name: "working",
enter: _,
cancel: function(promise) {
promise._setState(state_canceled);
},
done: done,
then: then,
_completed: completed,
_error: error,
_notify: _,
_progress: progress,
_setCompleteValue: setCompleteValue,
_setErrorValue: setErrorValue
};
// Waiting state, if a promise is completed with a value which is itself a promise
// (has a then() method) it signs up to be informed when that child promise is
// fulfilled at which point it will be fulfilled with that value.
//
state_waiting = {
name: "waiting",
enter: function(promise) {
var waitedUpon = promise._value;
// We can special case our own intermediate promises which are not in a
// terminal state by just pushing this promise as a listener without
// having to create new indirection functions
if (waitedUpon instanceof ThenPromise &&
waitedUpon._state !== state_error &&
waitedUpon._state !== state_success) {
pushListener(waitedUpon, { promise: promise });
} else {
var error: any = function(value) {
if (waitedUpon._errorId) {
promise._chainedError(value, waitedUpon);
} else {
// Because this is an interop boundary we want to indicate that this
// error has been handled by the promise infrastructure before we
// begin a new handling chain.
//
callonerror(promise, value, detailsForHandledError, waitedUpon, error);
promise._error(value);
}
};
error.handlesOnError = true;
waitedUpon.then(
promise._completed.bind(promise),
error,
promise._progress.bind(promise)
);
}
},
cancel: function(promise) {
promise._setState(state_waiting_canceled);
},
done: done,
then: then,
_completed: completed,
_error: error,
_notify: _,
_progress: progress,
_setCompleteValue: setCompleteValue,
_setErrorValue: setErrorValue
};
// Waiting canceled state, when a promise has been in a waiting state and receives a
// request to cancel its pending work it will forward that request to the child promise
// and then waits to be informed of the result. This promise moves itself into the
// canceling state but understands that the child promise may instead push it to a
// different state.
//
state_waiting_canceled = {
name: "waiting_canceled",
enter: function(promise) {
// Initiate a transition to canceling. Triggering a cancel on the promise
// that we are waiting upon may result in a different state transition
// before the state machine pump runs again.
promise._setState(state_canceling);
var waitedUpon = promise._value;
if (waitedUpon.cancel) {
waitedUpon.cancel();
}
},
cancel: _,
done: done,
then: then,
_completed: completed,
_error: error,
_notify: _,
_progress: progress,
_setCompleteValue: setCompleteValue,
_setErrorValue: setErrorValue
};
// Canceled state, moves to the canceling state and then tells the promise to do
// whatever it might need to do on cancelation.
//
state_canceled = {
name: "canceled",
enter: function(promise) {
// Initiate a transition to canceling. The _cancelAction may change the state
// before the state machine pump runs again.
promise._setState(state_canceling);
promise._cancelAction();
},
cancel: _,
done: done,
then: then,
_completed: completed,
_error: error,
_notify: _,
_progress: progress,
_setCompleteValue: setCompleteValue,
_setErrorValue: setErrorValue
};
// Canceling state, commits to the promise moving to an error state with an error
// object whose 'name' and 'message' properties contain the string "Canceled"
//
state_canceling = {
name: "canceling",
enter: function(promise) {
var error = new Error(canceledName);
error.name = error.message;
promise._value = error;
promise._setState(state_error_notify);
},
cancel: _,
done: _,
then: _,
_completed: _,
_error: _,
_notify: _,
_progress: _,
_setCompleteValue: _,
_setErrorValue: _
};
// Success notify state, moves a promise to the success state and notifies all children
//
state_success_notify = {
name: "complete_notify",
enter: function(promise) {
promise.done = CompletePromise.prototype.done;
promise.then = CompletePromise.prototype.then;
if (promise._listeners) {
var queue = [promise];
var p;
while (queue.length) {
p = queue.shift();
p._state._notify(p, queue);
}
}
promise._setState(state_success);
},
cancel: _,
done: null, /*error to get here */
then: null, /*error to get here */
_completed: _,
_error: _,
_notify: notifySuccess,
_progress: _,
_setCompleteValue: _,
_setErrorValue: _
};
// Success state, moves a promise to the success state and does NOT notify any children.
// Some upstream promise is owning the notification pass.
//
state_success = {
name: "success",
enter: function(promise) {
promise.done = CompletePromise.prototype.done;
promise.then = CompletePromise.prototype.then;
promise._cleanupAction();
},
cancel: _,
done: null, /*error to get here */
then: null, /*error to get here */
_completed: _,
_error: _,
_notify: notifySuccess,
_progress: _,
_setCompleteValue: _,
_setErrorValue: _
};
// Error notify state, moves a promise to the error state and notifies all children
//
state_error_notify = {
name: "error_notify",
enter: function(promise) {
promise.done = ErrorPromise.prototype.done;
promise.then = ErrorPromise.prototype.then;
if (promise._listeners) {
var queue = [promise];
var p;
while (queue.length) {
p = queue.shift();
p._state._notify(p, queue);
}
}
promise._setState(state_error);
},
cancel: _,
done: null, /*error to get here*/
then: null, /*error to get here*/
_completed: _,
_error: _,
_notify: notifyError,
_progress: _,
_setCompleteValue: _,
_setErrorValue: _
};
// Error state, moves a promise to the error state and does NOT notify any children.
// Some upstream promise is owning the notification pass.
//
state_error = {
name: "error",
enter: function(promise) {
promise.done = ErrorPromise.prototype.done;
promise.then = ErrorPromise.prototype.then;
promise._cleanupAction();
},
cancel: _,
done: null, /*error to get here*/
then: null, /*error to get here*/
_completed: _,
_error: _,
_notify: notifyError,
_progress: _,
_setCompleteValue: _,
_setErrorValue: _
};
//
// The statemachine implementation follows a very particular pattern, the states are specified
// as static stateless bags of functions which are then indirected through the state machine
// instance (a Promise). As such all of the functions on each state have the promise instance
// passed to them explicitly as a parameter and the Promise instance members do a little
// dance where they indirect through the state and insert themselves in the argument list.
//
// We could instead call directly through the promise states however then every caller
// would have to remember to do things like pumping the state machine to catch state transitions.
//
export class PromiseStateMachine {
static supportedForProcessing: boolean = false;
_listeners: any = null;
_nextState: any = null;
_state: any = null;
_value: any = null;
cancel(): void {
///
///
/// Attempts to cancel the fulfillment of a promised value. If the promise hasn't
/// already been fulfilled and cancellation is supported, the promise enters
/// the error state with a value of Error("Canceled").
///
///
this._state.cancel(this);
this._run();
}
done(onComplete, onError, onProgress): void { //Promise_done
///
///
/// Allows you to specify the work to be done on the fulfillment of the promised value,
/// the error handling to be performed if the promise fails to fulfill
/// a value, and the handling of progress notifications along the way.
///
/// After the handlers have finished executing, this function throws any error that would have been returned
/// from then() as a promise in the error state.
///
///
/// The function to be called if the promise is fulfilled successfully with a value.
/// The fulfilled value is passed as the single argument. If the value is null,
/// the fulfilled value is returned. The value returned
/// from the function becomes the fulfilled value of the promise returned by
/// then(). If an exception is thrown while executing the function, the promise returned
/// by then() moves into the error state.
///
///
/// The function to be called if the promise is fulfilled with an error. The error
/// is passed as the single argument. If it is null, the error is forwarded.
/// The value returned from the function is the fulfilled value of the promise returned by then().
///
///
/// the function to be called if the promise reports progress. Data about the progress
/// is passed as the single argument. Promises are not required to support
/// progress.
///
///
this._state.done(this, onComplete, onError, onProgress);
}
then(onComplete, onError, onProgress): any {//Promise_then
///
///
/// Allows you to specify the work to be done on the fulfillment of the promised value,
/// the error handling to be performed if the promise fails to fulfill
/// a value, and the handling of progress notifications along the way.
///
///
/// The function to be called if the promise is fulfilled successfully with a value.
/// The value is passed as the single argument. If the value is null, the value is returned.
/// The value returned from the function becomes the fulfilled value of the promise returned by
/// then(). If an exception is thrown while this function is being executed, the promise returned
/// by then() moves into the error state.
///
///
/// The function to be called if the promise is fulfilled with an error. The error
/// is passed as the single argument. If it is null, the error is forwarded.
/// The value returned from the function becomes the fulfilled value of the promise returned by then().
///
///
/// The function to be called if the promise reports progress. Data about the progress
/// is passed as the single argument. Promises are not required to support
/// progress.
///
///
/// The promise whose value is the result of executing the complete or
/// error function.
///
///
return this._state.then(this, onComplete, onError, onProgress);
}
_chainedError(value, context): any {
var result = this._state._error(this, value, detailsForChainedError, context);
this._run();
return result;
}
_completed(value): any {
var result = this._state._completed(this, value);
this._run();
return result;
}
_error(value): any {
var result = this._state._error(this, value, detailsForError);
this._run();
return result;
}
_progress(value): void {
this._state._progress(this, value);
}
_setState(state): void {
this._nextState = state;
}
_setCompleteValue(value): void {
this._state._setCompleteValue(this, value);
this._run();
}
_setChainedErrorValue(value, context): any {
var result = this._state._setErrorValue(this, value, detailsForChainedError, context);
this._run();
return result;
}
_setExceptionValue(value): any {
var result = this._state._setErrorValue(this, value, detailsForException);
this._run();
return result;
}
_run(): void {
while (this._nextState) {
this._state = this._nextState;
this._nextState = null;
this._state.enter(this);
}
}
}
//
// Implementations of shared state machine code.
//
function completed(promise, value) {
var targetState;
if (value && typeof value === "object" && typeof value.then === "function") {
targetState = state_waiting;
} else {
targetState = state_success_notify;
}
promise._value = value;
promise._setState(targetState);
}
function createErrorDetails(exception?, error?, promise?, id?, parent?, handler?) {
return {
exception: exception,
error: error,
promise: promise,
handler: handler,
id: id,
parent: parent
};
}
function detailsForHandledError(promise, errorValue, context, handler) {
var exception = context._isException;
var errorId = context._errorId;
return createErrorDetails(
exception ? errorValue : null,
exception ? null : errorValue,
promise,
errorId,
context,
handler
);
}
function detailsForChainedError(promise, errorValue, context) {
var exception = context._isException;
var errorId = context._errorId;
setErrorInfo(promise, errorId, exception);
return createErrorDetails(
exception ? errorValue : null,
exception ? null : errorValue,
promise,
errorId,
context
);
}
function detailsForError(promise, errorValue) {
var errorId = ++error_number;
setErrorInfo(promise, errorId);
return createErrorDetails(
null,
errorValue,
promise,
errorId
);
}
function detailsForException(promise, exceptionValue) {
var errorId = ++error_number;
setErrorInfo(promise, errorId, true);
return createErrorDetails(
exceptionValue,
null,
promise,
errorId
);
}
function done(promise, onComplete, onError, onProgress) {
var asyncOpID = _Trace._traceAsyncOperationStarting("WinJS.Promise.done");
pushListener(promise, { c: onComplete, e: onError, p: onProgress, asyncOpID: asyncOpID });
}
function error(promise, value, onerrorDetails, context) {
promise._value = value;
callonerror(promise, value, onerrorDetails, context);
promise._setState(state_error_notify);
}
function notifySuccess(promise, queue) {
var value = promise._value;
var listeners = promise._listeners;
if (!listeners) {
return;
}
promise._listeners = null;
var i, len;
for (i = 0, len = Array.isArray(listeners) ? listeners.length : 1; i < len; i++) {
var listener = len === 1 ? listeners : listeners[i];
var onComplete = listener.c;
var target = listener.promise;
_Trace._traceAsyncOperationCompleted(listener.asyncOpID, _Global.Debug && _Global.Debug.MS_ASYNC_OP_STATUS_SUCCESS);
if (target) {
_Trace._traceAsyncCallbackStarting(listener.asyncOpID);
try {
target._setCompleteValue(onComplete ? onComplete(value) : value);
} catch (ex) {
target._setExceptionValue(ex);
} finally {
_Trace._traceAsyncCallbackCompleted();
}
if (target._state !== state_waiting && target._listeners) {
queue.push(target);
}
} else {
CompletePromise.prototype.done.call(promise, onComplete);
}
}
}
function notifyError(promise, queue) {
var value = promise._value;
var listeners = promise._listeners;
if (!listeners) {
return;
}
promise._listeners = null;
var i, len;
for (i = 0, len = Array.isArray(listeners) ? listeners.length : 1; i < len; i++) {
var listener = len === 1 ? listeners : listeners[i];
var onError = listener.e;
var target = listener.promise;
var errorID = _Global.Debug && (value && value.name === canceledName ? _Global.Debug.MS_ASYNC_OP_STATUS_CANCELED : _Global.Debug.MS_ASYNC_OP_STATUS_ERROR);
_Trace._traceAsyncOperationCompleted(listener.asyncOpID, errorID);
if (target) {
var asyncCallbackStarted = false;
try {
if (onError) {
_Trace._traceAsyncCallbackStarting(listener.asyncOpID);
asyncCallbackStarted = true;
if (!onError.handlesOnError) {
callonerror(target, value, detailsForHandledError, promise, onError);
}
target._setCompleteValue(onError(value));
} else {
target._setChainedErrorValue(value, promise);
}
} catch (ex) {
target._setExceptionValue(ex);
} finally {
if (asyncCallbackStarted) {
_Trace._traceAsyncCallbackCompleted();
}
}
if (target._state !== state_waiting && target._listeners) {
queue.push(target);
}
} else {
ErrorPromise.prototype.done.call(promise, null, onError);
}
}
}
function callonerror(promise, value, onerrorDetailsGenerator?, context?, handler?) {
if (promiseEventListeners._listeners[errorET]) {
if (value instanceof Error && value.message === canceledName) {
return;
}
promiseEventListeners.dispatchEvent(errorET, onerrorDetailsGenerator(promise, value, context, handler));
}
}
function progress(promise, value) {
var listeners = promise._listeners;
if (listeners) {
var i, len;
for (i = 0, len = Array.isArray(listeners) ? listeners.length : 1; i < len; i++) {
var listener = len === 1 ? listeners : listeners[i];
var onProgress = listener.p;
if (onProgress) {
try { onProgress(value); } catch (ex) { }
}
if (!(listener.c || listener.e) && listener.promise) {
listener.promise._progress(value);
}
}
}
}
function pushListener(promise, listener) {
var listeners = promise._listeners;
if (listeners) {
// We may have either a single listener (which will never be wrapped in an array)
// or 2+ listeners (which will be wrapped). Since we are now adding one more listener
// we may have to wrap the single listener before adding the second.
listeners = Array.isArray(listeners) ? listeners : [listeners];
listeners.push(listener);
} else {
listeners = listener;
}
promise._listeners = listeners;
}
// The difference beween setCompleteValue()/setErrorValue() and complete()/error() is that setXXXValue() moves
// a promise directly to the success/error state without starting another notification pass (because one
// is already ongoing).
function setErrorInfo(promise, errorId?, isException?) {
promise._isException = isException || false;
promise._errorId = errorId;
}
function setErrorValue(promise, value, onerrorDetails, context) {
promise._value = value;
callonerror(promise, value, onerrorDetails, context);
promise._setState(state_error);
}
function setCompleteValue(promise, value) {
var targetState;
if (value && typeof value === "object" && typeof value.then === "function") {
targetState = state_waiting;
} else {
targetState = state_success;
}
promise._value = value;
promise._setState(targetState);
}
function then(promise, onComplete, onError, onProgress) {
var result = new ThenPromise(promise);
var asyncOpID = _Trace._traceAsyncOperationStarting("WinJS.Promise.then");
pushListener(promise, { promise: result, c: onComplete, e: onError, p: onProgress, asyncOpID: asyncOpID });
return result;
}
//
// Internal implementation detail promise, ThenPromise is created when a promise needs
// to be returned from a then() method.
//
class ThenPromise extends PromiseStateMachine {
static supportedForProcessing: boolean = false;
_creator: any = null;
_stack: any = null;
constructor(creator) {
super();
if (tagWithStack && (tagWithStack === true || (tagWithStack & tag.thenPromise))) {
this._stack = Promise._getStack();
}
this._creator = creator;
this._setState(state_created);
this._run();
}
_cancelAction() {
if (this._creator) {
this._creator.cancel();
}
}
_cleanupAction() {
this._creator = null;
}
}
//
// Slim promise implementations for already completed promises, these are created
// under the hood on synchronous completion paths as well as by WinJS.Promise.wrap
// and WinJS.Promise.wrapError.
//
class ErrorPromise {
static supportedForProcessing: boolean = false;
_value: any = null;
_stack: any = null;
constructor(value) {
if (tagWithStack && (tagWithStack === true || (tagWithStack & tag.errorPromise))) {
this._stack = Promise._getStack();
}
this._value = value;
callonerror(this, value, detailsForError);
}
cancel() {
///
///
/// Attempts to cancel the fulfillment of a promised value. If the promise hasn't
/// already been fulfilled and cancellation is supported, the promise enters
/// the error state with a value of Error("Canceled").
///
///
}
done(unused, onError) {
///
///
/// Allows you to specify the work to be done on the fulfillment of the promised value,
/// the error handling to be performed if the promise fails to fulfill
/// a value, and the handling of progress notifications along the way.
///
/// After the handlers have finished executing, this function throws any error that would have been returned
/// from then() as a promise in the error state.
///
///
/// The function to be called if the promise is fulfilled successfully with a value.
/// The fulfilled value is passed as the single argument. If the value is null,
/// the fulfilled value is returned. The value returned
/// from the function becomes the fulfilled value of the promise returned by
/// then(). If an exception is thrown while executing the function, the promise returned
/// by then() moves into the error state.
///
///
/// The function to be called if the promise is fulfilled with an error. The error
/// is passed as the single argument. If it is null, the error is forwarded.
/// The value returned from the function is the fulfilled value of the promise returned by then().
///
///
/// the function to be called if the promise reports progress. Data about the progress
/// is passed as the single argument. Promises are not required to support
/// progress.
///
///
var value = this._value;
if (onError) {
try {
if (!onError.handlesOnError) {
callonerror(null, value, detailsForHandledError, this, onError);
}
var result = onError(value);
if (result && typeof result === "object" && typeof result.done === "function") {
// If a promise is returned we need to wait on it.
result.done();
}
return;
} catch (ex) {
value = ex;
}
}
if (value instanceof Error && value.message === canceledName) {
// suppress cancel
return;
}
// force the exception to be thrown asyncronously to avoid any try/catch blocks
//
Promise._doneHandler(value);
}
then(unused, onError) {
///
///
/// Allows you to specify the work to be done on the fulfillment of the promised value,
/// the error handling to be performed if the promise fails to fulfill
/// a value, and the handling of progress notifications along the way.
///
///
/// The function to be called if the promise is fulfilled successfully with a value.
/// The value is passed as the single argument. If the value is null, the value is returned.
/// The value returned from the function becomes the fulfilled value of the promise returned by
/// then(). If an exception is thrown while this function is being executed, the promise returned
/// by then() moves into the error state.
///
///
/// The function to be called if the promise is fulfilled with an error. The error
/// is passed as the single argument. If it is null, the error is forwarded.
/// The value returned from the function becomes the fulfilled value of the promise returned by then().
///
///
/// The function to be called if the promise reports progress. Data about the progress
/// is passed as the single argument. Promises are not required to support
/// progress.
///
///
/// The promise whose value is the result of executing the complete or
/// error function.
///
///
// If the promise is already in a error state and no error handler is provided
// we optimize by simply returning the promise instead of creating a new one.
//
if (!onError) { return this; }
var result;
var value = this._value;
try {
if (!onError.handlesOnError) {
callonerror(null, value, detailsForHandledError, this, onError);
}
result = new CompletePromise(onError(value));
} catch (ex) {
// If the value throw from the error handler is the same as the value
// provided to the error handler then there is no need for a new promise.
//
if (ex === value) {
result = this;
} else {
result = new ExceptionPromise(ex);
}
}
return result;
}
}
class ExceptionPromise extends ErrorPromise {
static supportedForProcessing: boolean = false;
constructor(value) {
super(value);
if (tagWithStack && (tagWithStack === true || (tagWithStack & tag.exceptionPromise))) {
this._stack = Promise._getStack();
}
this._value = value;
callonerror(this, value, detailsForException);
}
}
class CompletePromise {
static supportedForProcessing: boolean = false;
_value: any = null;
_stack: any = null;
constructor(value) {
if (tagWithStack && (tagWithStack === true || (tagWithStack & tag.completePromise))) {
this._stack = Promise._getStack();
}
if (value && typeof value === "object" && typeof value.then === "function") {
var result = new ThenPromise(null);
result._setCompleteValue(value);
return result;
}
this._value = value;
}
cancel() {
///
///
/// Attempts to cancel the fulfillment of a promised value. If the promise hasn't
/// already been fulfilled and cancellation is supported, the promise enters
/// the error state with a value of Error("Canceled").
///
///
}
done(onComplete) {
///
///
/// Allows you to specify the work to be done on the fulfillment of the promised value,
/// the error handling to be performed if the promise fails to fulfill
/// a value, and the handling of progress notifications along the way.
///
/// After the handlers have finished executing, this function throws any error that would have been returned
/// from then() as a promise in the error state.
///
///
/// The function to be called if the promise is fulfilled successfully with a value.
/// The fulfilled value is passed as the single argument. If the value is null,
/// the fulfilled value is returned. The value returned
/// from the function becomes the fulfilled value of the promise returned by
/// then(). If an exception is thrown while executing the function, the promise returned
/// by then() moves into the error state.
///
///
/// The function to be called if the promise is fulfilled with an error. The error
/// is passed as the single argument. If it is null, the error is forwarded.
/// The value returned from the function is the fulfilled value of the promise returned by then().
///
///
/// the function to be called if the promise reports progress. Data about the progress
/// is passed as the single argument. Promises are not required to support
/// progress.
///
///
if (!onComplete) { return; }
try {
var result = onComplete(this._value);
if (result && typeof result === "object" && typeof result.done === "function") {
result.done();
}
} catch (ex) {
// force the exception to be thrown asynchronously to avoid any try/catch blocks
Promise._doneHandler(ex);
}
}
then(onComplete): any {
///
///
/// Allows you to specify the work to be done on the fulfillment of the promised value,
/// the error handling to be performed if the promise fails to fulfill
/// a value, and the handling of progress notifications along the way.
///
///
/// The function to be called if the promise is fulfilled successfully with a value.
/// The value is passed as the single argument. If the value is null, the value is returned.
/// The value returned from the function becomes the fulfilled value of the promise returned by
/// then(). If an exception is thrown while this function is being executed, the promise returned
/// by then() moves into the error state.
///
///
/// The function to be called if the promise is fulfilled with an error. The error
/// is passed as the single argument. If it is null, the error is forwarded.
/// The value returned from the function becomes the fulfilled value of the promise returned by then().
///
///
/// The function to be called if the promise reports progress. Data about the progress
/// is passed as the single argument. Promises are not required to support
/// progress.
///
///
/// The promise whose value is the result of executing the complete or
/// error function.
///
///
try {
// If the value returned from the completion handler is the same as the value
// provided to the completion handler then there is no need for a new promise.
//
var newValue = onComplete ? onComplete(this._value) : this._value;
return newValue === this._value ? this : new CompletePromise(newValue);
} catch (ex) {
return new ExceptionPromise(ex);
}
}
}
//
// Promise is the user-creatable WinJS.Promise object.
//
function timeout(timeoutMS) {
var id;
return new Promise(
function(c) {
if (timeoutMS) {
id = _Global.setTimeout(c, timeoutMS);
} else {
_BaseCoreUtils._setImmediate(c);
}
},
function() {
if (id) {
_Global.clearTimeout(id);
}
}
);
}
function timeoutWithPromise(timeout, promise) {
var cancelPromise = function() { promise.cancel(); };
var cancelTimeout = function() { timeout.cancel(); };
timeout.then(cancelPromise);
promise.then(cancelTimeout, cancelTimeout);
return promise;
}
var staticCanceledPromise;
export class Promise extends PromiseStateMachine {
static supportedForProcessing: boolean = false;
get _veryExpensiveTagWithStack() { return tagWithStack; }
set _veryExpensiveTagWithStack(value) { tagWithStack = value; }
static _veryExpensiveTagWithStack_tag: any = tag;
///
/// Canceled promise value, can be returned from a promise completion handler
/// to indicate cancelation of the promise chain.
///
static get cancel(): any {
return (staticCanceledPromise = staticCanceledPromise || new ErrorPromise(new _ErrorFromName(canceledName)));
}
_oncancel: any = null;
_stack: any = null;
constructor(init, oncancel?) {
///
///
/// A promise provides a mechanism to schedule work to be done on a value that
/// has not yet been computed. It is a convenient abstraction for managing
/// interactions with asynchronous APIs.
///
///
/// The function that is called during construction of the promise. The function
/// is given three arguments (complete, error, progress). Inside this function
/// you should add event listeners for the notifications supported by this value.
///
///
/// The function to call if a consumer of this promise wants
/// to cancel its undone work. Promises are not required to
/// support cancellation.
///
///
super();
if (tagWithStack && (tagWithStack === true || (tagWithStack & tag.promise))) {
this._stack = Promise._getStack();
}
this._oncancel = oncancel;
this._setState(state_created);
this._run();
try {
var complete = this._completed.bind(this);
var error = this._error.bind(this);
var progress = this._progress.bind(this);
init(complete, error, progress);
} catch (ex) {
this._setExceptionValue(ex);
}
}
_cancelAction() {
if (this._oncancel) {
try { this._oncancel(); } catch (ex) { }
}
}
_cleanupAction() { this._oncancel = null; }
static addEventListener(eventType, listener, capture) {
///
///
/// Adds an event listener to the control.
///
///
/// The type (name) of the event.
///
///
/// The listener to invoke when the event is raised.
///
///
/// Specifies whether or not to initiate capture.
///
///
promiseEventListeners.addEventListener(eventType, listener, capture);
}
static any(values) {
///
///
/// Returns a promise that is fulfilled when one of the input promises
/// has been fulfilled.
///
///
/// An array that contains promise objects or objects whose property
/// values include promise objects.
///
///
/// A promise that on fulfillment yields the value of the input (complete or error).
///
///
return new Promise(
function(complete, error) {
var keys = Object.keys(values);
if (keys.length === 0) {
complete();
}
var canceled = 0;
keys.forEach(function(key) {
Promise.as(values[key]).then(
function() { complete({ key: key, value: values[key] }); },
function(e) {
if (e instanceof Error && e.name === canceledName) {
if ((++canceled) === keys.length) {
complete(Promise.cancel);
}
return;
}
error({ key: key, value: values[key] });
}
);
});
},
function() {
var keys = Object.keys(values);
keys.forEach(function(key) {
var promise = Promise.as(values[key]);
if (typeof promise.cancel === "function") {
promise.cancel();
}
});
}
);
}
static as(value) {
///
///
/// Returns a promise. If the object is already a promise it is returned;
/// otherwise the object is wrapped in a promise.
///
///
/// The value to be treated as a promise.
///
///
/// A promise.
///
///
if (value && typeof value === "object" && typeof value.then === "function") {
return value;
}
return new CompletePromise(value);
}
static dispatchEvent(eventType, details) {
///
///
/// Raises an event of the specified type and properties.
///
///
/// The type (name) of the event.
///
///
/// The set of additional properties to be attached to the event object.
///
///
/// Specifies whether preventDefault was called on the event.
///
///
return promiseEventListeners.dispatchEvent(eventType, details);
}
static is(value) {
///
///
/// Determines whether a value fulfills the promise contract.
///
///
/// A value that may be a promise.
///
///
/// true if the specified value is a promise, otherwise false.
///
///
return value && typeof value === "object" && typeof value.then === "function";
}
static join(values) {
///
///
/// Creates a promise that is fulfilled when all the values are fulfilled.
///
///
/// An object whose fields contain values, some of which may be promises.
///
///
/// A promise whose value is an object with the same field names as those of the object in the values parameter, where
/// each field value is the fulfilled value of a promise.
///
///
return new Promise(
function(complete, error, progress) {
var keys = Object.keys(values);
var errors = Array.isArray(values) ? [] : {};
var results = Array.isArray(values) ? [] : {};
var undefineds = 0;
var pending = keys.length;
var argDone = function(key) {
if ((--pending) === 0) {
var errorCount = Object.keys(errors).length;
if (errorCount === 0) {
complete(results);
} else {
var canceledCount = 0;
keys.forEach(function(key) {
var e = errors[key];
if (e instanceof Error && e.name === canceledName) {
canceledCount++;
}
});
if (canceledCount === errorCount) {
complete(Promise.cancel);
} else {
error(errors);
}
}
} else {
progress({ Key: key, Done: true });
}
};
keys.forEach(function(key) {
var value = values[key];
if (value === undefined) {
undefineds++;
} else {
Promise.then(value,
function(value) { results[key] = value; argDone(key); },
function(value) { errors[key] = value; argDone(key); }
);
}
});
pending -= undefineds;
if (pending === 0) {
complete(results);
return;
}
},
function() {
Object.keys(values).forEach(function(key) {
var promise = Promise.as(values[key]);
if (typeof promise.cancel === "function") {
promise.cancel();
}
});
}
);
}
static removeEventListener(eventType, listener, capture) {
///
///
/// Removes an event listener from the control.
///
///
/// The type (name) of the event.
///
///
/// The listener to remove.
///
///
/// Specifies whether or not to initiate capture.
///
///
promiseEventListeners.removeEventListener(eventType, listener, capture);
}
static then(value, onComplete, onError, onProgress?) {
///
///
/// A static version of the promise instance method then().
///
///
/// the value to be treated as a promise.
///
///
/// The function to be called if the promise is fulfilled with a value.
/// If it is null, the promise simply
/// returns the value. The value is passed as the single argument.
///
///
/// The function to be called if the promise is fulfilled with an error. The error
/// is passed as the single argument.
///
///
/// The function to be called if the promise reports progress. Data about the progress
/// is passed as the single argument. Promises are not required to support
/// progress.
///
///
/// A promise whose value is the result of executing the provided complete function.
///
///
return Promise.as(value).then(onComplete, onError, onProgress);
}
static thenEach(values, onComplete, onError, onProgress?) {
///
///
/// Performs an operation on all the input promises and returns a promise
/// that has the shape of the input and contains the result of the operation
/// that has been performed on each input.
///
///
/// A set of values (which could be either an array or an object) of which some or all are promises.
///
///
/// The function to be called if the promise is fulfilled with a value.
/// If the value is null, the promise returns the value.
/// The value is passed as the single argument.
///
///
/// The function to be called if the promise is fulfilled with an error. The error
/// is passed as the single argument.
///
///
/// The function to be called if the promise reports progress. Data about the progress
/// is passed as the single argument. Promises are not required to support
/// progress.
///
///
/// A promise that is the result of calling Promise.join on the values parameter.
///
///
var result = Array.isArray(values) ? [] : {};
Object.keys(values).forEach(function(key) {
result[key] = Promise.as(values[key]).then(onComplete, onError, onProgress);
});
return Promise.join(result);
}
static timeout(time, promise?) {
///
///
/// Creates a promise that is fulfilled after a timeout.
///
///
/// The timeout period in milliseconds. If this value is zero or not specified
/// setImmediate is called, otherwise setTimeout is called.
///
///
/// A promise that will be canceled if it doesn't complete before the
/// timeout has expired.
///
///
/// A promise that is completed asynchronously after the specified timeout.
///
///
var to = timeout(time);
return promise ? timeoutWithPromise(to, promise) : to;
}
static wrap(value) {
///
///
/// Wraps a non-promise value in a promise. You can use this function if you need
/// to pass a value to a function that requires a promise.
///
///
/// Some non-promise value to be wrapped in a promise.
///
///
/// A promise that is successfully fulfilled with the specified value
///
///
return new CompletePromise(value);
}
static wrapError(error) {
///
///
/// Wraps a non-promise error value in a promise. You can use this function if you need
/// to pass an error to a function that requires a promise.
///
///
/// A non-promise error value to be wrapped in a promise.
///
///
/// A promise that is in an error state with the specified value.
///
///
return new ErrorPromise(error);
}
static _cancelBlocker(input, oncancel): any {
//
// Returns a promise which on cancelation will still result in downstream cancelation while
// protecting the promise 'input' from being canceled which has the effect of allowing
// 'input' to be shared amoung various consumers.
//
if (!Promise.is(input)) {
return Promise.wrap(input);
}
var complete;
var error;
var output = new Promise(
function(c, e) {
complete = c;
error = e;
},
function() {
complete = null;
error = null;
oncancel && oncancel();
}
);
input.then(
function(v) { complete && complete(v); },
function(e) { error && error(e); }
);
return output;
}
static _getStack() {
if (_Global.Debug && _Global.Debug.debuggerEnabled) {
try { throw new Error(); } catch (e) { return e.stack; }
}
}
static _doneHandler = (value) => {
_BaseCoreUtils._setImmediate(function Promise_done_rethrow() {
throw value;
});
};
onerror: any; //to be used with event creation
}
Object.defineProperties(Promise, _Events.createEventProperties(errorET));
// var _export = {
// PromiseStateMachine: PromiseStateMachine,
// Promise: Promise,
// state_created: state_created
// };
// export = _export;