SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Member
    Join Date
    Feb 2010
    Posts
    7
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Asynchronous process problem

    Hi,

    I have a problem with my code:

    Code JavaScript:
    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

  2. #2
    SitePoint Member
    Join Date
    Feb 2010
    Posts
    7
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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.


Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •