Class decorators and async process
Brendan Eich
brendan at mozilla.org
Sat May 23 18:54:35 UTC 2015
Gray Zhang wrote:
>
> Hi all:
>
> I’m wondering if there is any way to combine a class decorator and an
> async process together? A common case would be a generic IoC
> implementation:
>
First, too many undefined terms and made-up syntax extensions just makes
for confusion. Can you define "async process"? To optimize I'll assume
you mean async function, a function returning a promise.
> Since in JavaScript IoC
>
IoC = Inversion of Control -- just checking!
> we load runtime modules async by a config file, the interface may be:
>
> |{Promise} ioc.getComponent({string} componentName)
> |
Nicer to use reserved type annotation syntax:
| ioc.getComponent(componentName: string): Promise|
I hope that's what {T} D means!
> which resolves the returned Promise giving required instance of
> |componentName|, and this is a method that cannot be sync since we
> need a config file to map |componentName| to its implementing module
> and load the module lazily (for performance reason)
>
> This is an async process so if we add a decorator to a class property:
>
> |function inject(name) {
> return (target, key, descriptor) {|
Missing `function` after `return`?
> |
> // Note this returns a promise, not the actual property value
> descriptor.initializer = () => ioc.getComponent(name);
> }
> }
>
> class Hero {
> @inject('knife')
> weapon = null|
So the decorator calls the anonymous function with key='knife',
target=instance-of-Hero, and descriptor the property descriptor,
extended with .initializer?
BTW the idea of using property descriptors for decorators got push-back
and an alternative suggestion at the March TC39 meeting.
> |
>
> hit(enemy) {
> enemy.heath -= (this.weapon.power - enemy.defense);
> }
> }
> |
>
> This code may not work, but nobody likes there injected properties to
> be all async getters and all code logics become unnecessarily complex
> by introducing so many async processes
>
Have you read about `await` and `async` in ES7?
> How so we think of such common case, should I just make the
> |ioc.getComponent| sync without considerations to performance,
>
"performance" is not really accurate: responsiveness and even deadlock
avoidance come to mind. If you're talking about a browser API, then you
can't do sync loading (apart from bad old sync XHR), so async/await is
the way to go.
> or should I give up the decorator solution?
>
Is the decorator idea based on extended property descriptors actually
being used, e.g., with Babel? Sorry if I missed it.
/be
More information about the es-discuss
mailing list