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

cache delayed promises #85

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 deletions src/injector.js
Original file line number Diff line number Diff line change
Expand Up @@ -218,12 +218,9 @@ class Injector {

resolving.push(token);

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

// Once all dependencies (promises) are resolved, instantiate.
return Promise.all(args).then(function(args) {
instance = Promise.all(args).then(function(args) {
injector._cache.delete(token);

try {
instance = provider.create(args);
} catch (e) {
Expand All @@ -264,6 +263,8 @@ class Injector {
// a promise or not.
return instance;
});
this._cache.set(token, instance);
return instance;
}

try {
Expand Down
11 changes: 11 additions & 0 deletions test/async.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,17 @@ describe('async', function() {
expect(controller.promise).toBePromiseLike();
});

it('should not instantiate multiple times in case of delayed instantiating', function(done) {
var injector = new Injector([fetchUsers]);

Promise.all([
injector.getPromise(UserController),
injector.getPromise(UserController)
]).then(function(result) {
expect(result[0]).toBe(result[1]);
done();
});
});

// regression
it('should not cache TransientScope', function(done) {
Expand Down