0

So I have this code to check if a date in the database has an event. I want to set the hasEvent to true in the array of weeks and days. The problem is at the end it logs the same line 4 times. Why does it do this and how could I go about solving it?

This is the code I currently use:

for (var i = 0; i < weeks.length-1; i++) {
    for (var j = 0; j < weeks[i].days.length-1; j++) {
        var datum = weeks[i].days[j];

        db.collection('events').doc(datum.year + "-" + datum.month + "-" + datum.day).get().then(function(doc) {
            if (doc.exists) {
                console.log(datum.year + "-" + datum.month + "-" + datum.day + " is true" + " i " + i + " j " + j);
                weeks[i].days[j].hasEvent = "true";
            }else{
                weeks[i].days[j].hasEvent = "false";
            }
        });

    }
}

It keeps returning 2018-04-28 is true i 5 j 6 I use the firestore database. the collection is called events. in events I have a document that has the date as name and in there I have some info.

Kristianmitk
  • 4,528
  • 5
  • 26
  • 46
RamonRobben
  • 483
  • 1
  • 5
  • 18
  • 1
    https://stackoverflow.com/q/750486/5351549 – ewcz Apr 28 '18 at 20:27
  • Use `let` for `i` and `j` and use `const` for `datum` instead of `var`, because var has (function scope) so it will keep the last value as the sync code is done, but const and let will have (block scope) – Samir Aleido Apr 28 '18 at 20:45

1 Answers1

1

It's because when your callback after your async calls is executed the loop is finished and at that moment i holds the value weeks.length-2 and j the value weeks[i].days.length-2.

You could use Array#forEach() instead the for-loop to avoid that behaviour and make sure every async call is wrapped within its own function block that holds a proper index value.

Kristianmitk
  • 4,528
  • 5
  • 26
  • 46
  • Yeah I tought it would do something like that but I tought the .then would take the current I and J and wait for the promise to resolve before continue. but that is not the case appearantly. – RamonRobben Apr 28 '18 at 20:31
  • @RamonRobben: Promises just provide a nice way to "manage" async "values". They don't change how the language works (i.e. they don't halt execution. If they did there wasn't a need for callbacks in the first place). – Felix Kling Apr 28 '18 at 20:33
  • @FelixKling I mean currently I really dislike the way promises work. They seem to make everything so much harder. Maybe its because I do not fully understand how they work. or maybe they just are really difficult to work with. – RamonRobben Apr 28 '18 at 21:02