我正在编写一个Chrome扩展程序,可以调用google翻译api。一旦我得到翻译的单词,我想将它添加到一个数组中,但我相信它是异步的,我不知道如何将它传递给数组,以便它可用在主线程上。
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));
此输出
translatedWords ["hola"]
现在应该是
translatedWords ["hola","que"]
我怎样才能做到这一点?谢谢!
答案 0 :(得分:0)
这不是chrome扩展的问题,这是ajax请求中回调的问题。当您调用$ .ajax时,响应是异步的。这意味着它不会等待返回,直到它返回以继续执行您的方法。所以你的操作顺序是:
您需要将依赖于结果的逻辑放入实际的成功回调中,如下所示:
$.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));
});