I'm trying to write a script that will allow me to quickly examine how a word changes when translated multiple times by Google translate. Unfortunately, I'm not very experienced with Javascript and I can't pin down the source of the problem I'm having:
func开发者_如何学编程tion initialize() {
var word = "Hello";
var english = [word];
var german = [];
document.write("1");
var i = 0;
for (i=0; i<10; i++) {
google.language.translate(english[i], 'en', 'de', function(result) {
if (!result.error) {
german.push(result.translation);
document.write(result.translation);
}
else {
document.write(result.error.message);
}
document.write("2");
});
document.write("3");
google.language.translate(german[i], 'de', 'en', function(result) {
if (!result.error) {
english.push( result.translation );
document.write ( result.translation );
}
else {
document.write(result.error.message);
}
document.write("4");
});
document.write("5");
}
}
google.setOnLoadCallback(initialize);
As you can see, the second call to google.language.translate takes as an argument the result of the first call. I expect to see something like this in the document when this is run:
1Hallo23Hello45Hallo23Hello45Hallo23Hello45 ...
Instead I get 13Hallo2 and a crash. Because it prints 1and 3 (ie it executes the doc.write("3") before it executes all of the first call to translate) I suspect some sort of asynchronous behavior is going on. I'm used code that executes in the order I wrote it! Help! Ideally I'd like to know how I can get the rest of the loop to only execute after the first call to google translate has returned.
That's indeed a synchronization issue. When you call the first google.language.translate
, you pass in a callback, but that callback isn't executed immediately - only after translate
gets a translation from the server. In the mean time, the code continues to run, and executes the second google.language.translate
, passing in german[i]
, which is probably undefined at that point.
To serialize the execution of those a-sync calls, you can place the second call to google.language.translate
inside the callback of the first one, after the document.write("2")
. This will ensure german[i]
is set before used.
精彩评论