I'm writing a chrome extension which makes a call to google translate api. Once I get the translated word I'd like to add it into an array but I believe it's async and I'm not sure how to pass it to the array so that it's available on the main thread.
var translatedWords = ["hola"];
var text = "what";
var key="******************";
var source="en";
var dest="es";
$.ajax({
type: "GET",
url: "https://www.googleapis.com/language/translate/v2key="+key+"&source="+source+"&target="+dest+"&q="+text
}).done(function(response) {
//SET Translated word
var WordTranslated = response.data.translations[0].translatedText;
//populate into array
translatedWords.push(WordTranslated);
}).fail(function(response) {
console.log("FAILURE: " + JSON.stringify(response));
});
console.log("translatedWords " + JSON.stringify(translatedWords));
And this outputs
translatedWords ["hola"]
where it should now be
translatedWords ["hola","que"]
How can I accomplish this? Thanks!
This isn't an issue with the chrome extension, this is an issue with callbacks in an ajax request. When you call $.ajax, the response is asynchronous. This means that it doesn't wait to return until it returns to keep executing your method. So your order of operations is:
You need to put your logic that depends on the results into the actual success callback, like this: