Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing a cumulative value to a variable from within a function that's in a for loop, then recalling that variable elsewhere

Tags:

javascript

I'm having trouble understanding a particular concept.

The general problem is storing a cumulative value to a variable from within a function that's in a for loop, then recalling the variable elsewhere.

I'll explain all of the parts first:

I call to an API to get the value of a key. The call looks something like this.

keyName = API.key('keyName'); 
keyName.get(function(err, value) {
   console.log(value);
 });

However, I need to get a whole bunch of these keys, so I put the call into a for loop. I also want to store the cumulative value in the variable fullString

var fullString = [];

for (var i = 0; i < numberOfKeys; i++) {      
  keyName = API.key('keyName' + i);
  keyName.get(function(err, value) {
    fullString += value;

    console.log(fullString);
  });
}

Let's say:

keyName0 : 'a'
keyName1 : 'b'
keyName2 : 'c'

When the loop runs, I'll get this (which I understand):

a
ab
abc

The thing that I don't understand is, if I reference fullString outside of the function it returns null i.e.

var fullString = [];

for (var i = 0; i < numberOfKeys; i++) {      
  keyName = API.key('keyName' + i);
  keyName.get(function(err, value) {
    fullString += value;
  });
  console.log(fullString);
}
console.log(fullString);

Both of the above console.log's will return null, shouldn't they log the full value i.e. abc

like image 701
YoDK Avatar asked Dec 02 '25 07:12

YoDK


1 Answers

The problem is not with scoping but with asynchronicity. You are logging the value of fullString before this is resolved. If you put the log call just after the fullString += value statement you will see that the variable is in fact equal to abc (on the last iteration). However because get() is async fullString will be update after you called console.log.

update: to get the final value i suggest you read on javascript promises. AngularJS has a very nice implementation of it derived by Kris Kowal's Q, read here.

in your case it would work something like (just an idea):

var fullString = keyname.getAll().done(function (data) { return data; });
like image 92
Joe Minichino Avatar answered Dec 03 '25 23:12

Joe Minichino



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!