2

I am new to Javascript and call back functions. is this the correct way to do a call back? when i test i get an infinite loop. I want to retrieve from the database and store in an object's variable to use in 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'];
}
Marcus
  • 822
  • 1
  • 8
  • 27
Kenan Farmer
  • 35
  • 1
  • 6
  • 2
    You cannot return synchronously from `getSport` if it calls an asynchronous function. You should read [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](http://stackoverflow.com/q/23667086/218196) and [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call). You also have a problem with `this`, see [How to access the correct `this` / context inside a callback?](http://stackoverflow.com/q/20279484/218196) for that. – Felix Kling Apr 04 '16 at 15:45
  • These are all from https://stackoverflow.com/questions/tagged/javascript?sort=frequent btw. – Felix Kling Apr 04 '16 at 15:45
  • 1
    `this.getSport` is a getter, not a function - and the getter recursively calls itself ad infinitum, er, stack overflow. – Bergi Apr 04 '16 at 16:21
  • If I realized correctly, the behavior you want seems match to the [ES6 generator](https://davidwalsh.name/es6-generators) pattern. That is, do `getSport` asynchronouslly, then `yield` `rload` result, then do `getSport` again ..., until some condition matched. – hankchiutw Apr 04 '16 at 17:05

1 Answers1

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.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175