javascript - 初始化后在对象中公开和使用特权方法
问题描述
我有两个对象构造函数“类”。第一个运行异步操作并在数据准备好时执行回调。在回调中,我初始化了第二个函数。
我希望能够通过包装函数公开某些属性。这些属性将根据需要每隔一段时间进行轮询。我不确定在查询这些属性时,第二个对象是否已经初始化。
var Wrapper = function(){
//This may take a while to finish
var foo = new Foo(function(err,data){
bar = new Bar(data);
});
//this can be queried every few 100ms
this.getProp(){
return this.bar.getProp();
}
}
var w = new Wrapper();
w.getProp(); //Cannot read property 'getProp' of undefined
公开此类数据的最佳方式是什么?
解决方案
我不会说这是最好的方法。它更像是一个让你的伪代码工作的例子。
function Foo(cb) {
// simulate initialization delay
setTimeout(() => cb(null, {
wookies: 12
}), 3000);
}
function Bar(data) {
this.data = data;
}
function Wrapper() {
const setBar = (err, data) => this.bar = new Bar(data);
//This may take a while to finish
new Foo(setBar);
//this can be queried every few 100ms
this.getProp = function() {
if (!this.bar) {
// not ready yet
console.log('still awaiting initialization');
return;
}
return this.bar.data;
}
}
const w = new Wrapper();
function go() {
const x = w.getProp();
if (!x) {
setTimeout(go, 100);
} else {
console.log(x);
}
}
go();
推荐阅读
- regex - 在一组字符和一些整数之后获取第一个字母的正则表达式是什么?
- java - 在 AnyLogic 中执行存活率计算
- android - 在根目录中运行 make 命令时如何在不同的目录中运行可执行文件?
- python - 如何将创建的文件移动到刚刚创建的目录中?
- c# - C#如何获取2个单独的类值节点并将它们写入数据表/dgv
- pivot - 计算平均值:基于另一列 Excel 数据透视表和 PowerBI 中的唯一值的最大值
- django - API 不发送电子邮件
- r - 使用 R odbc 包将日期插入 Oracle 时时区偏移和丢失毫秒
- javascript - 多级侧边栏菜单,如 Glazed Main
- authentication - 如何将 bcrypt 嵌入到 mongose API 调用中?