use Promise instead of Future

This commit is contained in:
vsavkin 2014-10-10 15:44:56 -04:00
parent f524a89cb6
commit 1a7d5160f2
14 changed files with 97 additions and 82 deletions

View File

@ -1,5 +1,5 @@
import {Type} from 'facade/lang';
import {Future} from 'facade/async';
import {Promise} from 'facade/async';
import {Element} from 'facade/dom';
//import {ProtoView} from './view';
import {TemplateLoader} from './template_loader';
@ -13,14 +13,14 @@ export class Compiler {
}
/**
* # Why future?
* # Why promise?
* - compilation will load templates. Instantiating views before templates are loaded will
* complicate the Directive code. BENEFIT: view instantiation become synchrnous.
* # Why result that is independent of injector?
* - don't know about injector in deserialization
* - compile does not need the injector, only the ViewFactory does
*/
compile(component:Type, element:Element/* = null*/):Future/*<ProtoView>*/ {
compile(component:Type, element:Element/* = null*/):Promise/*<ProtoView>*/ {
return null;
}

View File

@ -1,11 +1,11 @@
import {Future} from 'facade/async';
import {Promise} from 'facade/async';
//import {Document} from 'facade/dom';
export class TemplateLoader {
constructor() {}
load(url:String):Future/*<Document>*/ {
load(url:String):Promise/*<Document>*/ {
return null;
}
}

View File

@ -7,7 +7,7 @@ export class Inject {
}
}
export class InjectFuture {
export class InjectPromise {
@CONST()
constructor(token) {
this.token = token;

View File

@ -5,21 +5,21 @@ import {Key} from './key';
export class Dependency {
@FIELD('final key:Key')
@FIELD('final asFuture:bool')
@FIELD('final asPromise:bool')
@FIELD('final lazy:bool')
constructor(key:Key, asFuture:boolean, lazy:boolean) {
constructor(key:Key, asPromise:boolean, lazy:boolean) {
this.key = key;
this.asFuture = asFuture;
this.asPromise = asPromise;
this.lazy = lazy;
}
}
export class Binding {
constructor(key:Key, factory:Function, dependencies:List, providedAsFuture:boolean) {
constructor(key:Key, factory:Function, dependencies:List, providedAsPromise:boolean) {
this.key = key;
this.factory = factory;
this.dependencies = dependencies;
this.providedAsFuture = providedAsFuture;
this.providedAsPromise = providedAsPromise;
}
}

View File

@ -43,7 +43,7 @@ export class AsyncBindingError extends ProviderError {
super(key, function (keys:List) {
var first = stringify(ListWrapper.first(keys).token);
return `Cannot instantiate ${first} synchronously. ` +
`It is provided as a future!${constructResolvingPath(keys)}`;
`It is provided as a promise!${constructResolvingPath(keys)}`;
});
}
}

View File

@ -3,14 +3,14 @@ import {Binding, BindingBuilder, bind} from './binding';
import {ProviderError, NoProviderError, InvalidBindingError,
AsyncBindingError, CyclicDependencyError, InstantiationError} from './exceptions';
import {Type, isPresent, isBlank} from 'facade/lang';
import {Future, FutureWrapper} from 'facade/async';
import {Promise, PromiseWrapper} from 'facade/async';
import {Key} from './key';
var _constructing = new Object();
class _Waiting {
constructor(future:Future) {
this.future = future;
constructor(promise:Promise) {
this.promise = promise;
}
}
function _isWaiting(obj):boolean {
@ -53,12 +53,12 @@ export class Injector {
return ListWrapper.createFixedSize(Key.numberOfKeys() + 1);
}
_getByKey(key:Key, returnFuture:boolean, returnLazy:boolean) {
_getByKey(key:Key, returnPromise:boolean, returnLazy:boolean) {
if (returnLazy) {
return () => this._getByKey(key, returnFuture, false);
return () => this._getByKey(key, returnPromise, false);
}
var strategy = returnFuture ? this._asyncStrategy : this._syncStrategy;
var strategy = returnPromise ? this._asyncStrategy : this._syncStrategy;
var instance = strategy.readFromCache(key);
if (isPresent(instance)) return instance;
@ -67,14 +67,14 @@ export class Injector {
if (isPresent(instance)) return instance;
if (isPresent(this._parent)) {
return this._parent._getByKey(key, returnFuture, returnLazy);
return this._parent._getByKey(key, returnPromise, returnLazy);
}
throw new NoProviderError(key);
}
_resolveDependencies(key:Key, binding:Binding, forceAsync:boolean):List {
try {
var getDependency = d => this._getByKey(d.key, forceAsync || d.asFuture, d.lazy);
var getDependency = d => this._getByKey(d.key, forceAsync || d.asPromise, d.lazy);
return ListWrapper.map(binding.dependencies, getDependency);
} catch (e) {
this._clear(key);
@ -139,7 +139,7 @@ class _SyncInjectorStrategy {
var binding = this.injector._getBinding(key);
if (isBlank(binding)) return null;
if (binding.providedAsFuture) throw new AsyncBindingError(key);
if (binding.providedAsPromise) throw new AsyncBindingError(key);
//add a marker so we can detect cyclic dependencies
this.injector._markAsConstructing(key);
@ -168,7 +168,7 @@ class _AsyncInjectorStrategy {
readFromCache(key:Key) {
if (key.token === Injector) {
return FutureWrapper.value(this.injector);
return PromiseWrapper.resolve(this.injector);
}
var instance = this.injector._getInstance(key);
@ -176,9 +176,9 @@ class _AsyncInjectorStrategy {
if (instance === _constructing) {
throw new CyclicDependencyError(key);
} else if (_isWaiting(instance)) {
return instance.future;
return instance.promise;
} else if (isPresent(instance)) {
return FutureWrapper.value(instance);
return PromiseWrapper.resolve(instance);
} else {
return null;
}
@ -192,19 +192,19 @@ class _AsyncInjectorStrategy {
this.injector._markAsConstructing(key);
var deps = this.injector._resolveDependencies(key, binding, true);
var depsFuture = FutureWrapper.wait(deps);
var depsPromise = PromiseWrapper.all(deps);
var future = FutureWrapper.catchError(depsFuture, (e) => this._errorHandler(key, e)).
var promise = PromiseWrapper.then(depsPromise, null, (e) => this._errorHandler(key, e)).
then(deps => this._findOrCreate(key, binding, deps)).
then(instance => this._cacheInstance(key, instance));
this.injector._setInstance(key, new _Waiting(future));
return future;
this.injector._setInstance(key, new _Waiting(promise));
return promise;
}
_errorHandler(key:Key, e):Future {
_errorHandler(key:Key, e):Promise {
if (e instanceof ProviderError) e.addKey(key);
return FutureWrapper.error(e);
return PromiseWrapper.reject(e);
}
_findOrCreate(key:Key, binding:Binding, deps:List) {

View File

@ -1,7 +1,7 @@
library facade.di.reflector;
import 'dart:mirrors';
import 'annotations.dart' show Inject, InjectFuture, InjectLazy;
import 'annotations.dart' show Inject, InjectPromise, InjectLazy;
import 'key.dart' show Key;
import 'binding.dart' show Dependency;
import 'exceptions.dart' show NoAnnotationError;
@ -34,14 +34,14 @@ class Reflector {
final metadata = p.metadata.map((m) => m.reflectee);
var inject = metadata.firstWhere((m) => m is Inject, orElse: () => null);
var injectFuture = metadata.firstWhere((m) => m is InjectFuture, orElse: () => null);
var injectPromise = metadata.firstWhere((m) => m is InjectPromise, orElse: () => null);
var injectLazy = metadata.firstWhere((m) => m is InjectLazy, orElse: () => null);
if (inject != null) {
return new Dependency(Key.get(inject.token), false, false);
} else if (injectFuture != null) {
return new Dependency(Key.get(injectFuture.token), true, false);
} else if (injectPromise != null) {
return new Dependency(Key.get(injectPromise.token), true, false);
} else if (injectLazy != null) {
return new Dependency(Key.get(injectLazy.token), false, true);

View File

@ -1,6 +1,6 @@
import {Type, isPresent} from 'facade/lang';
import {List} from 'facade/collection';
import {Inject, InjectFuture, InjectLazy} from './annotations';
import {Inject, InjectPromise, InjectLazy} from './annotations';
import {Key} from './key';
import {Dependency} from './binding';
import {NoAnnotationError} from './exceptions';
@ -31,7 +31,7 @@ class Reflector {
} else if (paramAnnotation instanceof Inject) {
return this._createDependency(paramAnnotation.token, false, false);
} else if (paramAnnotation instanceof InjectFuture) {
} else if (paramAnnotation instanceof InjectPromise) {
return this._createDependency(paramAnnotation.token, true, false);
} else if (paramAnnotation instanceof InjectLazy) {
@ -46,8 +46,8 @@ class Reflector {
}
}
_createDependency(token, asFuture, lazy):Dependency {
return new Dependency(Key.get(token), asFuture, lazy);
_createDependency(token, asPromise, lazy):Dependency {
return new Dependency(Key.get(token), asPromise, lazy);
}
}

View File

@ -1,12 +1,12 @@
import {ddescribe, describe, it, iit, xit, expect, beforeEach} from 'test_lib/test_lib';
import {Injector, Inject, InjectFuture, bind, Key} from 'di/di';
import {Future, FutureWrapper} from 'facade/async';
import {Injector, Inject, InjectPromise, bind, Key} from 'di/di';
import {Promise, PromiseWrapper} from 'facade/async';
class UserList {
}
function fetchUsers() {
return FutureWrapper.value(new UserList());
return PromiseWrapper.resolve(new UserList());
}
class SynchronousUserList {
@ -19,7 +19,7 @@ class UserController {
}
class AsyncUserController {
constructor(@InjectFuture(UserList) userList) {
constructor(@InjectPromise(UserList) userList) {
this.userList = userList;
}
}
@ -28,28 +28,28 @@ export function main() {
describe("async injection", function () {
describe("asyncGet", function () {
it('should return a future', function () {
it('should return a promise', function () {
var injector = new Injector([
bind(UserList).toAsyncFactory(fetchUsers)
]);
var p = injector.asyncGet(UserList);
expect(p).toBeFuture();
expect(p).toBePromise();
});
it('should return a future when the binding is sync', function () {
it('should return a promise when the binding is sync', function () {
var injector = new Injector([
SynchronousUserList
]);
var p = injector.asyncGet(SynchronousUserList);
expect(p).toBeFuture();
expect(p).toBePromise();
});
it("should return a future when the binding is sync (from cache)", function () {
it("should return a promise when the binding is sync (from cache)", function () {
var injector = new Injector([
UserList
]);
expect(injector.get(UserList)).toBeAnInstanceOf(UserList);
expect(injector.asyncGet(UserList)).toBeFuture();
expect(injector.asyncGet(UserList)).toBePromise();
});
it('should return the injector', function (done) {
@ -61,7 +61,7 @@ export function main() {
});
});
it('should return a future when instantiating a sync binding ' +
it('should return a promise when instantiating a sync binding ' +
'with an async dependency', function (done) {
var injector = new Injector([
bind(UserList).toAsyncFactory(fetchUsers),
@ -83,7 +83,7 @@ export function main() {
var ul1 = injector.asyncGet(UserList);
var ul2 = injector.asyncGet(UserList);
FutureWrapper.wait([ul1, ul2]).then(function (uls) {
PromiseWrapper.all([ul1, ul2]).then(function (uls) {
expect(uls[0]).toBe(uls[1]);
done();
});
@ -94,13 +94,13 @@ export function main() {
UserList
]);
var future = injector.asyncGet(UserList);
var promise = injector.asyncGet(UserList);
var ul = injector.get(UserList);
expect(future).toBeFuture();
expect(promise).toBePromise();
expect(ul).toBeAnInstanceOf(UserList);
future.then(function (ful) {
promise.then(function (ful) {
expect(ful).toBe(ul);
done();
});
@ -114,8 +114,8 @@ export function main() {
})
]);
var future = injector.asyncGet(UserController);
FutureWrapper.catchError(future, function (e) {
var promise = injector.asyncGet(UserController);
PromiseWrapper.then(promise, null, function (e) {
expect(e.message).toContain("Error during instantiation of UserList! (UserController -> UserList)");
done();
});
@ -129,7 +129,7 @@ export function main() {
]);
expect(() => injector.get(UserList))
.toThrowError('Cannot instantiate UserList synchronously. It is provided as a future!');
.toThrowError('Cannot instantiate UserList synchronously. It is provided as a promise!');
});
it('should throw when instantiating a sync binding with an dependency', function () {
@ -139,10 +139,10 @@ export function main() {
]);
expect(() => injector.get(UserController))
.toThrowError('Cannot instantiate UserList synchronously. It is provided as a future! (UserController -> UserList)');
.toThrowError('Cannot instantiate UserList synchronously. It is provided as a promise! (UserController -> UserList)');
});
it('should resolve synchronously when an async dependency requested as a future', function () {
it('should resolve synchronously when an async dependency requested as a promise', function () {
var injector = new Injector([
bind(UserList).toAsyncFactory(fetchUsers),
AsyncUserController
@ -150,10 +150,10 @@ export function main() {
var controller = injector.get(AsyncUserController);
expect(controller).toBeAnInstanceOf(AsyncUserController);
expect(controller.userList).toBeFuture();
expect(controller.userList).toBePromise();
});
it('should wrap sync dependencies into futures if required', function () {
it('should wrap sync dependencies into promises if required', function () {
var injector = new Injector([
bind(UserList).toFactory(() => new UserList()),
AsyncUserController
@ -161,7 +161,7 @@ export function main() {
var controller = injector.get(AsyncUserController);
expect(controller).toBeAnInstanceOf(AsyncUserController);
expect(controller.userList).toBeFuture();
expect(controller.userList).toBePromise();
});
});
});

View File

@ -3,20 +3,20 @@ library angular.core.facade.async;
import 'dart:async';
export 'dart:async' show Future;
class FutureWrapper {
static Future value(obj) {
class PromiseWrapper {
static Future resolve(obj) {
return new Future.value(obj);
}
static Future error(obj) {
static Future reject(obj) {
return new Future.error(obj);
}
static Future wait(List<Future> futures){
return Future.wait(futures);
static Future all(List<Future> promises){
return Future.wait(promises);
}
static Future catchError(Future future, Function onError){
return future.catchError(onError);
static Future then(Future promise, Function success, Function onError){
return promise.then(success, onError: onError);
}
}

View File

@ -1,20 +1,20 @@
export var Future = Promise;
export var Promise = window.Promise;
export class FutureWrapper {
static value(obj):Future {
return Future.resolve(obj);
export class PromiseWrapper {
static resolve(obj):Promise {
return Promise.resolve(obj);
}
static error(obj):Future {
return Future.reject(obj);
static reject(obj):Promise {
return Promise.reject(obj);
}
static wait(futures):Future {
if (futures.length == 0) return Future.resolve([]);
return Future.all(futures);
static all(promises):Promise {
if (promises.length == 0) return Promise.resolve([]);
return Promise.all(promises);
}
static catchError(future:Future, onError:Function):Future {
return future.catch(onError);
static then(promise:Promise, success:Function, rejection:Function):Promise {
return promise.then(success, rejection);
}
}

View File

@ -16,7 +16,7 @@ class Expect extends gns.Expect {
Expect(actual) : super(actual);
void toThrowError(message) => this.toThrowWith(message: message);
void toBeFuture() => _expect(actual is Future, equals(true));
void toBePromise() => _expect(actual is Future, equals(true));
Function get _expect => gns.guinness.matchers.expect;
}

View File

@ -19,14 +19,14 @@ window.print = function(msg) {
window.beforeEach(function() {
jasmine.addMatchers({
toBeFuture: function() {
toBePromise: function() {
return {
compare: function (actual, expectedClass) {
var pass = typeof actual === 'object' && typeof actual.then === 'function';
return {
pass: pass,
get message() {
return 'Expected ' + actual + ' to be a future';
return 'Expected ' + actual + ' to be a promise';
}
};
}

View File

@ -19,6 +19,8 @@ import {
} from 'traceur/src/syntax/TokenType';
import {ParseTreeWriter as JavaScriptParseTreeWriter, ObjectLiteralExpression} from 'traceur/src/outputgeneration/ParseTreeWriter';
import {ImportedBinding, BindingIdentifier} from 'traceur/src/syntax/trees/ParseTrees';
import {IdentifierToken} from 'traceur/src/syntax/IdentifierToken';
export class DartParseTreeWriter extends JavaScriptParseTreeWriter {
constructor(moduleName, outputPath) {
@ -183,6 +185,7 @@ export class DartParseTreeWriter extends JavaScriptParseTreeWriter {
case 'number': return 'num';
case 'boolean': return 'bool';
case 'string': return 'String';
case 'Promise': return 'Future';
default: return typeName;
}
}
@ -309,6 +312,18 @@ export class DartParseTreeWriter extends JavaScriptParseTreeWriter {
this.visitAny(tree.binding);
}
visitImportedBinding(tree) {
if (tree.binding && tree.binding.identifierToken) {
var b = tree.binding;
var t = b.identifierToken;
var token = new IdentifierToken(t.location, this.normalizeType_(t.value));
var binding = new BindingIdentifier(b.location, token);
super.visitImportedBinding(new ImportedBinding(tree.location, binding));
} else {
super.visitImportedBinding(tree);
}
}
visitImportSpecifierSet(tree) {
if (tree.specifiers.type == STAR) {
throw new Error('"*" syntax not supported');