0

I am trying to add some values to a set and its not working as intended. when i console.log, it shows set size is zero however when i expand it, it shows values aswell as size. I am assuming this is happening because of asynchronicity but i am not sure how to fix it. I have attached the code below. I have reviewed some of the other threads related to async code but i am still having trouble understanding it. I suppose i have to use promise and await? but i am not sure how and where. Any help would be appreciated. Thank you.

addWeeks() {
  let result: any;
  let weeksSet = new Set();
  forkJoin({
    weeksList: this.weeksService.getWeeksList(),
  }).subscribe((vals) => {
    const { weeksList } = vals;

    result = weeksList.body;

    if (result != null) {
      this.gridData = result["weeksList"];

      this.gridData.forEach((item) => {
        weeksSet.add(item);
      });
    }
  });
}

Screenshot of what i see when i console.log weeksSet.

screenshot

Phil
  • 157,677
  • 23
  • 242
  • 245
  • _"when i console.log weeksSet"_... **where** is this logging occurring in your code? – Phil Jul 21 '22 at 03:39
  • Check your vals object by doing console.log( vals)? or may be `result['weeksList']` – subodhkalika Jul 21 '22 at 03:43
  • @phil outside my function.. console.log(weeksSet) – programmer0892 Jul 21 '22 at 03:44
  • Outside _which_ function? It would be easier if you [edit] your question to show where but I don't think it will change this being closed as a duplicate – Phil Jul 21 '22 at 03:46
  • @subodhkalika i think the issue here is that i am trying to add items to set inside subscribe and so unless that is finished, the set will not have any items. I think i have to use promise and await here but i m not sure how. – programmer0892 Jul 21 '22 at 03:47
  • Keep in mind that a function named `subscribe()` probably fires multiple times, every time a particular event occurs. You'll need to factor that in when deciding how to handle values. I would probably pass in a callback function that you can call from `subscribe` – Phil Jul 21 '22 at 03:49
  • I haven't seen your code for the service but I believe you can do this : Instead of `forkJoin` do `const { weeksList } = await this.weeksService.getWeeksList()`. – subodhkalika Jul 21 '22 at 03:50

0 Answers0