Javascript Chrome Extension Passing Variable From AJAX to Array

95 views Asked by At

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!

1

There are 1 answers

2
Brian On

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:

  1. Make ajax call
  2. Run console.log statement
  3. Ajax statement returns, runs success

You need to put your logic that depends on the results into the actual success callback, like this:

$.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);

    console.log("translatedWords " + JSON.stringify(translatedWords));

    //Any other logic here as well
}).fail(function(response) {
    console.log("FAILURE: " + JSON.stringify(response));
});