思路:class里面异步获取数据,并设置给类里面的变量,constructor 里面是不允许异步操作的,通过设置静态方法来执行异步操作,见init() 。
class BaseShot {
static a = null
static _instance = null
constructor(props) {
console.log(BaseShot.a)
}
static async init(options) {
if(!BaseShot._instance) {
BaseShot.a = await BaseShot.setA()
BaseShot._instance = new BaseShot(options)
}
return BaseShot._instance
}
static setA() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(5)
}, 300)
})
}
get a() {
return BaseShot.a
}
}
const cfg = {
href: 'www.baidu.com',
}
async function test() {
const shot = await BaseShot.init(cfg)
console.log(shot.a)
}
test()
继承的写法:
class BaseShot {
static a = null
static _instance = null
constructor(props) {
}
static setA() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(5)
}, 300)
})
}
static async init(sup, options) {
if(!sup._instance) {
sup.a = await sup.setA()
console.log(sup.a)
sup._instance = new sup(options)
}
return PDF._instance
}
}
class PDF extends BaseShot{
constructor(props) {
super(props)
}
get a() {
return PDF.a
}
}
const cfg = {
href: 'www.baidu.com',
}
async function test() {
const pdf = await PDF.init(PDF)
console.dir(pdf)
console.log(pdf.a)
}
test()
|