1

I have this in a function:

for (i=0; i < toTranslateArray.length; i++)
{
    (function(i)
    {
        getTranslation(toTranslateArray[i],function(callback_result)
        {
            trans += callback_result;
        });         
    })(i);  
}
// code using last value of trans

I need to use last value of trans. I have seen a lot of examples but i just can`t make it work. Another answers same with my problem: link

Community
  • 1
  • 1
smotru
  • 433
  • 2
  • 8
  • 24
  • 1
    Is the order in which you are concatenating the results relevant? – Bergi Aug 14 '13 at 14:56
  • 3
    When you use `for-in`, there's no way to reliably know when you're at the last value, unless you count the properties beforehand. Is `toTranslateArray` an actual Array? If so, it becomes simpler, though you still shouldn't be using `for-in`, but rather a `for` statement. –  Aug 14 '13 at 14:57
  • What have you tried to make it work? Please show us your specific attempts otherwise we would need to refer you to that question with the same problem. – Bergi Aug 14 '13 at 14:58
  • @Bergi yes they are relevant. – smotru Aug 14 '13 at 14:58
  • the last value of trans is the one that has at the end of the loop – Swaroop Nagendra Aug 14 '13 at 14:58
  • Should be noted, as Bergi hinted at, that if it is an asynchronous function, you may not be able to guarantee the order of the results is what you expect. – shanet Aug 14 '13 at 14:59
  • 1
    @smotru: Then see [Why is using “for…in” with array iteration such a bad idea?](http://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-such-a-bad-idea) and notice that `getTranslation` is asynchronous. – Bergi Aug 14 '13 at 15:00
  • 1
    @CrazyTrain yes it is an array. I would use a for then. I will show you my new code in few mins. – smotru Aug 14 '13 at 15:01
  • for more details here is my complete function: [link](http://stackoverflow.com/questions/18214286/javascript-synchronous-functions-chrome-extension?noredirect=1#comment26730514_18214286) – smotru Aug 14 '13 at 15:02
  • I have edited my code. I just don`t understand how can i get the last value out of the for. – smotru Aug 14 '13 at 15:06

1 Answers1

1

This is a pretty standard way to deal with asynchronous loops (see also JavaScript closure inside loops – simple practical example):

var results = [];
for (var count=0; count<toTranslateArray.length; count++) (function(i) {
    getTranslation(toTranslateArray[count], function(res) {
        results[i] = res;
        if (! --count) { // when all results are settled (count is back to zero)
            var trans = results.join("");
            // code using trans
        }
    });           
})(count);

Notice this will only execute the code when there was at least one item in the array.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375