How do I call a method within a loop?

Asked

Viewed 171 times

0

I’m trying to perform a function ,which I have a call from another function within a loop, however the return function only loads the first method input. So, how do I call a method within a loop? Follows the code:

function 1:

componentesGrafico() {
    var i, j;
    var valores; 
    console.log(this.arraySlide[i]);
    for (i = 0; i < this.arraySlide.length;i++) {
        valores = this.db.queryDatabase(this.arraySlide[i]);
        console.log(valores); 
    }       

function 2:

queryDatabase(id) {
    var grupo = '/EMPRESA/COMPBI/';
    var db = this.afd.database.ref(grupo).orderByKey();
    var valores = new Array(); 
    db.startAt(id).endAt(id+"\uf8ff").on("child_added",function (snapshot) {
        valores.push(snapshot.key);
        console.log(snapshot.key);
    });
    return valores;
}
  • I just indented your code, without taking or adding anything. I seem to be missing a key lock somewhere.

  • the code compiles if you put a '}' key at the end of function 1, but my problem is the return of function two. It executes the 'loop' correctly, but my result and the first of the query in firebase.

  • 1

    Just so I can understand a little better. Does the second method at some point not perform an asynchronous function? If yes, it will not work this way because it will probably return a Promise. You will need to adjust your logic if that is so. But I’m not sure if he really does this asynchronous call. Maybe it’s a "north"!

1 answer

0

As Diego said: the 2nd function works asynchronously. When you return the array of values, it has not yet been initialized. You will need to place the function 2 body in function 1:

componentesGrafico() {
    var i, j;
    var valores; 
    console.log(this.arraySlide[i]);
    for (i = 0; i < this.arraySlide.length;i++) {
        valores = new Array();
        var grupo = '/EMPRESA/COMPBI/';
        var db = this.afd.database.ref(grupo).orderByKey();
        db.startAt(id).endAt(id+"\uf8ff").on("child_added",function (snapshot) {
            valores.push(snapshot.key);
            console.log(snapshot.key);
        });
        console.log(valores); 
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.