Skip to content
This repository was archived by the owner on Feb 26, 2024. It is now read-only.

Commit 3f827ec

Browse files
machardmachard
authored and
machard
committed
cache delayed promises
1 parent 70606e1 commit 3f827ec

File tree

2 files changed

+17
-5
lines changed

2 files changed

+17
-5
lines changed

src/injector.js

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -218,12 +218,9 @@ class Injector {
218218

219219
resolving.push(token);
220220

221-
// TODO(vojta): handle these cases:
221+
// TODO(vojta): handle this case:
222222
// 1/
223223
// - requested as promise (delayed)
224-
// - requested again as promise (before the previous gets resolved) -> cache the promise
225-
// 2/
226-
// - requested as promise (delayed)
227224
// - requested again sync (before the previous gets resolved)
228225
// -> error, but let it go inside to throw where exactly is the async provider
229226
var delayingInstantiation = wantPromise && provider.params.some((param) => !param.isPromise);
@@ -243,7 +240,9 @@ class Injector {
243240
resolving.pop();
244241

245242
// Once all dependencies (promises) are resolved, instantiate.
246-
return Promise.all(args).then(function(args) {
243+
instance = Promise.all(args).then(function(args) {
244+
injector._cache.delete(token);
245+
247246
try {
248247
instance = provider.create(args);
249248
} catch (e) {
@@ -264,6 +263,8 @@ class Injector {
264263
// a promise or not.
265264
return instance;
266265
});
266+
this._cache.set(token, instance);
267+
return instance;
267268
}
268269

269270
try {

test/async.spec.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,17 @@ describe('async', function() {
9797
expect(controller.promise).toBePromiseLike();
9898
});
9999

100+
it('should not instantiate multiple times in case of delayed instantiating', function(done) {
101+
var injector = new Injector([fetchUsers]);
102+
103+
Promise.all([
104+
injector.getPromise(UserController),
105+
injector.getPromise(UserController)
106+
]).then(function(result) {
107+
expect(result[0]).toBe(result[1]);
108+
done();
109+
});
110+
});
100111

101112
// regression
102113
it('should not cache TransientScope', function(done) {

0 commit comments

Comments
 (0)