Skip to content

Instantly share code, notes, and snippets.

@AStaroverov
Last active August 3, 2017 13:35
Show Gist options
  • Save AStaroverov/7c59be941cc564be3ca360b907af02b9 to your computer and use it in GitHub Desktop.
Save AStaroverov/7c59be941cc564be3ca360b907af02b9 to your computer and use it in GitHub Desktop.
JS decorator: async extend class
import forEach from 'lodash/lodash'
class Defer {
constructor () {
this.resolve = null
this.reject = null
this.promise = new Promise((resolve, reject) => {
this.resolve = resolve
this.reject = reject
})
Object.freeze(this)
}
}
function asyncExtend (mixins) {
return (target) => {
const defer = new Defer()
const proto = target.prototype
const _super = { ...proto }
target.waitAsyncExtend = defer.promise
if (!mixins) {
defer.resolve()
} else {
(async function () {
const loadedMixins = await Promise.all(mixins.map(f => f()))
forEach(loadedMixins, ({ mixin }) => {
forEach(mixin, (func, key) => {
proto[key] = async function () {
_super[key] && await _super[key].call(this)
func.call(this)
}
})
})
defer.resolve()
})()
}
return target
}
}
@asyncExtend([
() => import('any/path/to/mixin')
])
class Any {
async hi () {
await Any.waitAsyncExtend
console.log('HI...')
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment