-
-
Save AStaroverov/7c59be941cc564be3ca360b907af02b9 to your computer and use it in GitHub Desktop.
JS decorator: async extend class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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