Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Since you are using sync XHR, instead of ajax, you need to use a sync function to save data, instead of <code>chrome.storage</code>, which is async.</p> <p>In the <a href="http://developer.chrome.com/extensions/storage.html" rel="nofollow">chrome.storage</a> documentation, one of its features is</p> <blockquote> <ul> <li>It's asynchronous with bulk read and write operations, and therefore faster than the blocking and serial <code>localStorage</code> API.</li> </ul> </blockquote> <p>But being blocking (and sync) is what you want, so why don't you change to that API instead?</p> <p>Or even better:</p> <p>Convert your <code>getTranslation()</code> function to be async. You would only need to add a third parameter that would be a callback, and use it inside the nested callbacks (because if you do this, you can also use ajax instead of sync XHR).</p> <p>That way is the <em>right thing</em>, but if you feel lazy and want an easier way, just do the former and change <code>chrome.storage</code> to <code>localStorage</code> and you are done.</p> <p><strong>EDIT</strong>: I see you have already changed you function to be async. And it seems it works correctly, but you updated your question and you seem to have problems grasping why this line does not work:</p> <pre><code>console.log(translated); //this is first and empty </code></pre> <p>You need to understand how event oriented programming works. You may think that the line</p> <pre><code>for (counter in toTranslateArray) </code></pre> <p>which contains <code>getTranslation</code> means <strong>"do translation of every counter inside this toTranslateArray"</strong>, but actually means <strong>"fire a translation event for every counter inside this toTranslateArray"</strong>.</p> <p>That means when that <code>console.log</code> get executed this tasks <em>have just been fired</em>; it does not wait for it to be finished. Therefore translated is empty in that moment. And that's normal, is executed async.</p> <p>I don't know what you need to do with the <code>translated</code> var once is finished, but I would try to fire a different event once the last item of the array gets processed.</p> <p>But anyway, what you need is to do is to study some tutorial or something about event oriented programming so all this makes more sense to you.</p> <p>About the <code>localStorage</code>, I don't know, I found out about that as an alternative in the <code>chrome.storage</code> documentation, I really don't know how to use it in your case.</p> <p>But since javascript is event oriented, I really recommend you to learn events instead of just going back to sync. But is up to you.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload