我是Javascript的新手并回调函数。这是回电的正确方法吗?当我测试我得到一个无限循环。我想从数据库中检索并存储在一个对象的变量中,以便在getSport()中使用。
constructor(matchid) {
this.hasLoaded = false;
this.matchid = mid;
this.Match = {
"sport": "baskt",
"winner": -1,
};
}
rload(callback) {
this.hasLoaded = true;
matchDataBaseRef.child(this.mid)
.on("value", function (snapshot) {
this.Match = snapshot.val();
callback();
});
}
get getSport() {
if (!this.hasLoaded) {
this.rload(this.getSport);
}
return this.Match['sport'];
}
答案 0 :(得分:1)
That's not the right approach. You are trying to synchronize in this.getSport
. Instead, you should have your initialization inside the callback and do not infinitely call it. Let's suppose you have something like this:
function myTask(params) {
//do something
params.callback();
//do something
}
then you should not work with that like this unless you have a very good reason:
var foo = function() {
myTask({callback: foo});
};
Instead of it, in most cases you need something like this:
var foo = function(cb) {
myTask({callback: cb});
};
cb
needs to be defined though separately. So do not pass the wrapper function as a callback if that is not precisely what you want to do.