Since you are using sync XHR, instead of ajax, you need to use a sync function to save data, instead of
chrome.storage, which is async.
In the chrome.storage documentation, one of its features is
- It's asynchronous with bulk read and write operations, and therefore faster than the blocking and serial
But being blocking (and sync) is what you want, so why don't you change to that API instead?
Or even better:
getTranslation() 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).
That way is the right thing, but if you feel lazy and want an easier way, just do the former and change
localStorage and you are done.
EDIT: 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:
console.log(translated); //this is first and empty
You need to understand how event oriented programming works. You may think that the line
for (counter in toTranslateArray)
getTranslation means "do translation of every counter inside this toTranslateArray", but actually means "fire a translation event for every counter inside this toTranslateArray".
That means when that
console.log get executed this tasks have just been fired; it does not wait for it to be finished. Therefore translated is empty in that moment. And that's normal, is executed async.
I don't know what you need to do with the
translated var once is finished, but I would try to fire a different event once the last item of the array gets processed.
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.
localStorage, I don't know, I found out about that as an alternative in the
chrome.storage documentation, I really don't know how to use it in your case.