1

I have a function which is a loop by itself and in this loop I am creating an object. But when after the loop I'm trying to access the object properties, I get an response of undefined.

When I try to just console.log the object itself, I get it. The problem is with properties.

I would be grateful, if someone could help me. I did a good research, but didn't manage to find the solution. My case is very strange. Everything is good except the properties. I need the help of senior developers.

Here is the code.

var countMap = {};
  var counter = 0;
  $('#share_table_body').find('.js-post').each(function () {
    var totalCount = 0;
    $(this).find('.js-social').each(function () {
      var $this = $(this);
      var socialType = $(this).data('social-type');
      var url = $this.closest('.js-post').data('url');
      getShareStatus(url, socialType)
        .then(function (shareCount) {
          $this.text(shareCount);

          if (!countMap[socialType]) {
            countMap[socialType] = 0;
          }
          if (!countMap['total']) {
            countMap['total'] = 0;
          }

          countMap[socialType] += shareCount;

          totalCount += shareCount;

          countMap['total'] += shareCount;

          $this.siblings('.js-total').text(totalCount);
        })
        .fail(function (err) {
          $('.error-notice').removeClass('hidden');
          $this.css('color', 'red').text('!');
        });
    });
    counter++;
  });
  if (counter == $('#share_table_body').find('.js-post').length) {
    console.log(countMap);
    $('.total-facebook').text(countMap['facebook']);
  }
  • `getShareStatus` contains an asyncronous function – Beginner Feb 21 '17 at 06:08
  • This question is a duplicate, yes, but better answered by [Why is my variable unaltered after I modify it inside of a function?](http://stackoverflow.com/questions/23667086) than by the question referenced in the official duplication notice. – Old Pro Feb 21 '17 at 07:30

1 Answers1

0

Are you returning anything from your function? Specifically...

return countMap;

SoEzPz
  • 14,958
  • 8
  • 61
  • 64
  • No, I'm trying to access the countMap within the function, after checking that the loop is overed. console.log(countMap) is printing my output normally. But $('.total-facebook').text(countMap['facebook']) is not working. – Ashot Israelyan Feb 21 '17 at 05:45