Asynchronous process problem

Hi,

I have a problem with my code:


var google_translate = function(text) 
{
	google.language.translate(text, '', user_lang, function(result) {
	  	if (!result.error) {
			if (text != result.translation) {
				return result.translation;
			}
		}
		else {
			return text;
		}
	});
	
}

var old_text = "Dies ist ein Test #jdclub #c";
var hash_pattern = /([^#]+)|(#[\\w]+)/g;
var a_tweet_text = old_text.match(hash_pattern);
console.info(a_tweet_text);
var new_text = '';
$.each(a_tweet_text, function(index,value) {
	if (value.charAt(0) != '#' || value == " ") {
		var translated = google_translate(value);
		new_text += translated;
	}
	else {
		new_text += ' '+value+' ';
	}
});


I separate the string into strings that begin with a # and strings that don’t. I try and translate the normal strings, but when I check new_text it contains undefined for the translated segments. Using console.info, I see the texts being translated, but it’s obviously done asynchronously.

My question: is there any way to make the code “wait” for the result before continuing? I thought by extracting the translate code into a function would force the code to wait on “var translated=…” but apparently it doesn’t.

Any help/suggestion is appreciated!

Pier

I ‘solved’ my problem by putting what needed to be done with the result on the callback function of google_translate. It’s redundant and a hack, but I guess the asynchronous aspect of the problem forces me to do so.