ready-mixin
v2.0.0
Published
Ready mixin for classes with async constructor
Downloads
15
Readme
ready-mixin
You have class with async constructor and you don't want use callback in constructor or make inheritance from some event emitter? Try ready-mixin!
Installation
npm install ready-mixin
API
_ready(err, ...)
Resolve or reject ready promise.
ready()
Return ready promise.
return: Promise
onReady(callback, opts)
function
callback is node-style callback functionObject
[opts]boolean
[spread]
isReady()
Return current ready status.
return: boolean
Examples
import { mixin } from 'core-decorators'
import ReadyMixin from 'ready-mixin'
@mixin(ReadyMixin)
class User {
constructor (userId) {
db.load(userId, (err, data) => {
if (err === null) {
this._data = data
}
this._ready(err)
})
}
}
let user = new User(0)
user.ready
.then(() => {
console.log('user was loaded!')
}, (err) => {
console.log('error on loading user!', err)
})
spread in onReady
import { mixin } from 'core-decorators'
import ReadyMixin from 'ready-mixin'
@mixin(ReadyMixin)
class A {
constructor () {
setTimeout(() => { this._ready(null, 1, 2, 3) }, 1000)
}
}
let a = new A()
a.onReady((err, v1, v2, v3) => {
console.log(`Sum: ${v1 + v2 + v3}`) // Sum: 6
}, {spread: true})
License
Code released under the MIT license.