I have a lot of problems in my code because it is not synchronous. Here is an example of problem that i have in a chrome extension. This is my function
function getTranslation(a_data, callback)
{
var apiKey = '####'
var json_object = {};
var url = '###';
var xmlhttp;
var json_parsed = {};
storage.get('data', function(items)
{
json_object = {
'text': a_data,
'from' : items.data.from,
'to' : items.data.to
};
var json_data = JSON.stringify(json_object);
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST", url, false);
xmlhttp.setRequestHeader("Content-type","application/json");
xmlhttp.setRequestHeader("Authorization","##apiKey=" + apiKey);
xmlhttp.setRequestHeader("X-Requested-With","XMLHttpRequest");
xmlhttp.send(json_data);
json_parsed = JSON.parse(xmlhttp.responseText);
callback(json_parsed.translation);
});
}
This is how i use getTranslation function in another function:
for (counter in toTranslateArray)
{
getTranslation(toTranslateArray[counter],function(callback)
{
translated += callback;
console.log(translated); //this is second and works
});
}
console.log(translated); //this is first and empty
//code depending on translated
Is it something wrong there ?