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 {Type} from 'facade/lang';
import {Future} from 'facade/async'; import {Promise} from 'facade/async';
import {Element} from 'facade/dom'; import {Element} from 'facade/dom';
//import {ProtoView} from './view'; //import {ProtoView} from './view';
import {TemplateLoader} from './template_loader'; 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 * - compilation will load templates. Instantiating views before templates are loaded will
* complicate the Directive code. BENEFIT: view instantiation become synchrnous. * complicate the Directive code. BENEFIT: view instantiation become synchrnous.
* # Why result that is independent of injector? * # Why result that is independent of injector?
* - don't know about injector in deserialization * - don't know about injector in deserialization
* - compile does not need the injector, only the ViewFactory does * - 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; return null;
} }

View File

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

View File

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

View File

@ -5,21 +5,21 @@ import {Key} from './key';
export class Dependency { export class Dependency {
@FIELD('final key:Key') @FIELD('final key:Key')
@FIELD('final asFuture:bool') @FIELD('final asPromise:bool')
@FIELD('final lazy:bool') @FIELD('final lazy:bool')
constructor(key:Key, asFuture:boolean, lazy:boolean) { constructor(key:Key, asPromise:boolean, lazy:boolean) {
this.key = key; this.key = key;
this.asFuture = asFuture; this.asPromise = asPromise;
this.lazy = lazy; this.lazy = lazy;
} }
} }
export class Binding { 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.key = key;
this.factory = factory; this.factory = factory;
this.dependencies = dependencies; 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) { super(key, function (keys:List) {
var first = stringify(ListWrapper.first(keys).token); var first = stringify(ListWrapper.first(keys).token);
return `Cannot instantiate ${first} synchronously. ` + 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, import {ProviderError, NoProviderError, InvalidBindingError,
AsyncBindingError, CyclicDependencyError, InstantiationError} from './exceptions'; AsyncBindingError, CyclicDependencyError, InstantiationError} from './exceptions';
import {Type, isPresent, isBlank} from 'facade/lang'; import {Type, isPresent, isBlank} from 'facade/lang';
import {Future, FutureWrapper} from 'facade/async'; import {Promise, PromiseWrapper} from 'facade/async';
import {Key} from './key'; import {Key} from './key';
var _constructing = new Object(); var _constructing = new Object();
class _Waiting { class _Waiting {
constructor(future:Future) { constructor(promise:Promise) {
this.future = future; this.promise = promise;
} }
} }
function _isWaiting(obj):boolean { function _isWaiting(obj):boolean {
@ -53,12 +53,12 @@ export class Injector {
return ListWrapper.createFixedSize(Key.numberOfKeys() + 1); return ListWrapper.createFixedSize(Key.numberOfKeys() + 1);
} }
_getByKey(key:Key, returnFuture:boolean, returnLazy:boolean) { _getByKey(key:Key, returnPromise:boolean, returnLazy:boolean) {
if (returnLazy) { 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); var instance = strategy.readFromCache(key);
if (isPresent(instance)) return instance; if (isPresent(instance)) return instance;
@ -67,14 +67,14 @@ export class Injector {
if (isPresent(instance)) return instance; if (isPresent(instance)) return instance;
if (isPresent(this._parent)) { if (isPresent(this._parent)) {
return this._parent._getByKey(key, returnFuture, returnLazy); return this._parent._getByKey(key, returnPromise, returnLazy);
} }
throw new NoProviderError(key); throw new NoProviderError(key);
} }
_resolveDependencies(key:Key, binding:Binding, forceAsync:boolean):List { _resolveDependencies(key:Key, binding:Binding, forceAsync:boolean):List {
try { 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); return ListWrapper.map(binding.dependencies, getDependency);
} catch (e) { } catch (e) {
this._clear(key); this._clear(key);
@ -139,7 +139,7 @@ class _SyncInjectorStrategy {
var binding = this.injector._getBinding(key); var binding = this.injector._getBinding(key);
if (isBlank(binding)) return null; 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 //add a marker so we can detect cyclic dependencies
this.injector._markAsConstructing(key); this.injector._markAsConstructing(key);
@ -168,7 +168,7 @@ class _AsyncInjectorStrategy {
readFromCache(key:Key) { readFromCache(key:Key) {
if (key.token === Injector) { if (key.token === Injector) {
return FutureWrapper.value(this.injector); return PromiseWrapper.resolve(this.injector);
} }
var instance = this.injector._getInstance(key); var instance = this.injector._getInstance(key);
@ -176,9 +176,9 @@ class _AsyncInjectorStrategy {
if (instance === _constructing) { if (instance === _constructing) {
throw new CyclicDependencyError(key); throw new CyclicDependencyError(key);
} else if (_isWaiting(instance)) { } else if (_isWaiting(instance)) {
return instance.future; return instance.promise;
} else if (isPresent(instance)) { } else if (isPresent(instance)) {
return FutureWrapper.value(instance); return PromiseWrapper.resolve(instance);
} else { } else {
return null; return null;
} }
@ -192,19 +192,19 @@ class _AsyncInjectorStrategy {
this.injector._markAsConstructing(key); this.injector._markAsConstructing(key);
var deps = this.injector._resolveDependencies(key, binding, true); 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(deps => this._findOrCreate(key, binding, deps)).
then(instance => this._cacheInstance(key, instance)); then(instance => this._cacheInstance(key, instance));
this.injector._setInstance(key, new _Waiting(future)); this.injector._setInstance(key, new _Waiting(promise));
return future; return promise;
} }
_errorHandler(key:Key, e):Future { _errorHandler(key:Key, e):Promise {
if (e instanceof ProviderError) e.addKey(key); if (e instanceof ProviderError) e.addKey(key);
return FutureWrapper.error(e); return PromiseWrapper.reject(e);
} }
_findOrCreate(key:Key, binding:Binding, deps:List) { _findOrCreate(key:Key, binding:Binding, deps:List) {

View File

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

View File

@ -1,6 +1,6 @@
import {Type, isPresent} from 'facade/lang'; import {Type, isPresent} from 'facade/lang';
import {List} from 'facade/collection'; import {List} from 'facade/collection';
import {Inject, InjectFuture, InjectLazy} from './annotations'; import {Inject, InjectPromise, InjectLazy} from './annotations';
import {Key} from './key'; import {Key} from './key';
import {Dependency} from './binding'; import {Dependency} from './binding';
import {NoAnnotationError} from './exceptions'; import {NoAnnotationError} from './exceptions';
@ -31,7 +31,7 @@ class Reflector {
} else if (paramAnnotation instanceof Inject) { } else if (paramAnnotation instanceof Inject) {
return this._createDependency(paramAnnotation.token, false, false); return this._createDependency(paramAnnotation.token, false, false);
} else if (paramAnnotation instanceof InjectFuture) { } else if (paramAnnotation instanceof InjectPromise) {
return this._createDependency(paramAnnotation.token, true, false); return this._createDependency(paramAnnotation.token, true, false);
} else if (paramAnnotation instanceof InjectLazy) { } else if (paramAnnotation instanceof InjectLazy) {
@ -46,8 +46,8 @@ class Reflector {
} }
} }
_createDependency(token, asFuture, lazy):Dependency { _createDependency(token, asPromise, lazy):Dependency {
return new Dependency(Key.get(token), asFuture, lazy); 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 {ddescribe, describe, it, iit, xit, expect, beforeEach} from 'test_lib/test_lib';
import {Injector, Inject, InjectFuture, bind, Key} from 'di/di'; import {Injector, Inject, InjectPromise, bind, Key} from 'di/di';
import {Future, FutureWrapper} from 'facade/async'; import {Promise, PromiseWrapper} from 'facade/async';
class UserList { class UserList {
} }
function fetchUsers() { function fetchUsers() {
return FutureWrapper.value(new UserList()); return PromiseWrapper.resolve(new UserList());
} }
class SynchronousUserList { class SynchronousUserList {
@ -19,7 +19,7 @@ class UserController {
} }
class AsyncUserController { class AsyncUserController {
constructor(@InjectFuture(UserList) userList) { constructor(@InjectPromise(UserList) userList) {
this.userList = userList; this.userList = userList;
} }
} }
@ -28,28 +28,28 @@ export function main() {
describe("async injection", function () { describe("async injection", function () {
describe("asyncGet", function () { describe("asyncGet", function () {
it('should return a future', function () { it('should return a promise', function () {
var injector = new Injector([ var injector = new Injector([
bind(UserList).toAsyncFactory(fetchUsers) bind(UserList).toAsyncFactory(fetchUsers)
]); ]);
var p = injector.asyncGet(UserList); 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([ var injector = new Injector([
SynchronousUserList SynchronousUserList
]); ]);
var p = injector.asyncGet(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([ var injector = new Injector([
UserList UserList
]); ]);
expect(injector.get(UserList)).toBeAnInstanceOf(UserList); expect(injector.get(UserList)).toBeAnInstanceOf(UserList);
expect(injector.asyncGet(UserList)).toBeFuture(); expect(injector.asyncGet(UserList)).toBePromise();
}); });
it('should return the injector', function (done) { 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) { 'with an async dependency', function (done) {
var injector = new Injector([ var injector = new Injector([
bind(UserList).toAsyncFactory(fetchUsers), bind(UserList).toAsyncFactory(fetchUsers),
@ -83,7 +83,7 @@ export function main() {
var ul1 = injector.asyncGet(UserList); var ul1 = injector.asyncGet(UserList);
var ul2 = 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]); expect(uls[0]).toBe(uls[1]);
done(); done();
}); });
@ -94,13 +94,13 @@ export function main() {
UserList UserList
]); ]);
var future = injector.asyncGet(UserList); var promise = injector.asyncGet(UserList);
var ul = injector.get(UserList); var ul = injector.get(UserList);
expect(future).toBeFuture(); expect(promise).toBePromise();
expect(ul).toBeAnInstanceOf(UserList); expect(ul).toBeAnInstanceOf(UserList);
future.then(function (ful) { promise.then(function (ful) {
expect(ful).toBe(ul); expect(ful).toBe(ul);
done(); done();
}); });
@ -114,8 +114,8 @@ export function main() {
}) })
]); ]);
var future = injector.asyncGet(UserController); var promise = injector.asyncGet(UserController);
FutureWrapper.catchError(future, function (e) { PromiseWrapper.then(promise, null, function (e) {
expect(e.message).toContain("Error during instantiation of UserList! (UserController -> UserList)"); expect(e.message).toContain("Error during instantiation of UserList! (UserController -> UserList)");
done(); done();
}); });
@ -129,7 +129,7 @@ export function main() {
]); ]);
expect(() => injector.get(UserList)) 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 () { it('should throw when instantiating a sync binding with an dependency', function () {
@ -139,10 +139,10 @@ export function main() {
]); ]);
expect(() => injector.get(UserController)) 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([ var injector = new Injector([
bind(UserList).toAsyncFactory(fetchUsers), bind(UserList).toAsyncFactory(fetchUsers),
AsyncUserController AsyncUserController
@ -150,10 +150,10 @@ export function main() {
var controller = injector.get(AsyncUserController); var controller = injector.get(AsyncUserController);
expect(controller).toBeAnInstanceOf(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([ var injector = new Injector([
bind(UserList).toFactory(() => new UserList()), bind(UserList).toFactory(() => new UserList()),
AsyncUserController AsyncUserController
@ -161,7 +161,7 @@ export function main() {
var controller = injector.get(AsyncUserController); var controller = injector.get(AsyncUserController);
expect(controller).toBeAnInstanceOf(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'; import 'dart:async';
export 'dart:async' show Future; export 'dart:async' show Future;
class FutureWrapper { class PromiseWrapper {
static Future value(obj) { static Future resolve(obj) {
return new Future.value(obj); return new Future.value(obj);
} }
static Future error(obj) { static Future reject(obj) {
return new Future.error(obj); return new Future.error(obj);
} }
static Future wait(List<Future> futures){ static Future all(List<Future> promises){
return Future.wait(futures); return Future.wait(promises);
} }
static Future catchError(Future future, Function onError){ static Future then(Future promise, Function success, Function onError){
return future.catchError(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 { export class PromiseWrapper {
static value(obj):Future { static resolve(obj):Promise {
return Future.resolve(obj); return Promise.resolve(obj);
} }
static error(obj):Future { static reject(obj):Promise {
return Future.reject(obj); return Promise.reject(obj);
} }
static wait(futures):Future { static all(promises):Promise {
if (futures.length == 0) return Future.resolve([]); if (promises.length == 0) return Promise.resolve([]);
return Future.all(futures); return Promise.all(promises);
} }
static catchError(future:Future, onError:Function):Future { static then(promise:Promise, success:Function, rejection:Function):Promise {
return future.catch(onError); return promise.then(success, rejection);
} }
} }

View File

@ -16,7 +16,7 @@ class Expect extends gns.Expect {
Expect(actual) : super(actual); Expect(actual) : super(actual);
void toThrowError(message) => this.toThrowWith(message: message); 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; Function get _expect => gns.guinness.matchers.expect;
} }

View File

@ -19,14 +19,14 @@ window.print = function(msg) {
window.beforeEach(function() { window.beforeEach(function() {
jasmine.addMatchers({ jasmine.addMatchers({
toBeFuture: function() { toBePromise: function() {
return { return {
compare: function (actual, expectedClass) { compare: function (actual, expectedClass) {
var pass = typeof actual === 'object' && typeof actual.then === 'function'; var pass = typeof actual === 'object' && typeof actual.then === 'function';
return { return {
pass: pass, pass: pass,
get message() { 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'; } from 'traceur/src/syntax/TokenType';
import {ParseTreeWriter as JavaScriptParseTreeWriter, ObjectLiteralExpression} from 'traceur/src/outputgeneration/ParseTreeWriter'; 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 { export class DartParseTreeWriter extends JavaScriptParseTreeWriter {
constructor(moduleName, outputPath) { constructor(moduleName, outputPath) {
@ -183,6 +185,7 @@ export class DartParseTreeWriter extends JavaScriptParseTreeWriter {
case 'number': return 'num'; case 'number': return 'num';
case 'boolean': return 'bool'; case 'boolean': return 'bool';
case 'string': return 'String'; case 'string': return 'String';
case 'Promise': return 'Future';
default: return typeName; default: return typeName;
} }
} }
@ -309,6 +312,18 @@ export class DartParseTreeWriter extends JavaScriptParseTreeWriter {
this.visitAny(tree.binding); 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) { visitImportSpecifierSet(tree) {
if (tree.specifiers.type == STAR) { if (tree.specifiers.type == STAR) {
throw new Error('"*" syntax not supported'); throw new Error('"*" syntax not supported');