Javascript synchronous functions - chrome extension -


this question has answer here:

i have lot of problems in code because not synchronous. here example of problem have in chrome extension. function

function gettranslation(a_data, callback) {             var apikey = '####'         var json_object = {};     var url = '###';     var xmlhttp;        var json_parsed = {};      storage.get('data', function(items)      {          json_object = {               'text': a_data,             'from' : items.data.from,             'to' : items.data.to          };         var json_data = json.stringify(json_object);          if (window.xmlhttprequest)         {             xmlhttp=new xmlhttprequest();         }         else         {             xmlhttp=new activexobject("microsoft.xmlhttp");         }          xmlhttp.open("post", url, false);         xmlhttp.setrequestheader("content-type","application/json");                   xmlhttp.setrequestheader("authorization","##apikey=" + apikey);                               xmlhttp.setrequestheader("x-requested-with","xmlhttprequest");                               xmlhttp.send(json_data);          json_parsed = json.parse(xmlhttp.responsetext);         callback(json_parsed.translation);     });                       } 

this how use gettranslation function in function:

for (counter in totranslatearray) {     gettranslation(totranslatearray[counter],function(callback)     {         translated += callback;         console.log(translated); //this second , works     });    } console.log(translated); //this first , empty //code depending on translated 

is wrong there ?

since using sync xhr, instead of ajax, need use sync function save data, instead of chrome.storage, async.

in chrome.storage documentation, 1 of features is

  • it's asynchronous bulk read , write operations, , therefore faster blocking , serial localstorage api.

but being blocking (and sync) want, why don't change api instead?

or better:

convert gettranslation() function async. need add third parameter callback, , use inside nested callbacks (because if this, can use ajax instead of sync xhr).

that way right thing, if feel lazy , want easier way, former , change chrome.storage localstorage , done.

edit: see have changed function async. , seems works correctly, updated question , seem have problems grasping why line not work:

console.log(translated); //this first , empty 

you need understand how event oriented programming works. may think line

for (counter in totranslatearray) 

which contains gettranslation means "do translation of every counter inside totranslatearray", means "fire translation event every counter inside totranslatearray".

that means when console.log executed tasks have been fired; not wait finished. therefore translated empty in moment. , that's normal, executed async.

i don't know need translated var once finished, try fire different event once last item of array gets processed.

but anyway, need study tutorial or event oriented programming makes more sense you.

about localstorage, don't know, found out alternative in chrome.storage documentation, don't know how use in case.

but since javascript event oriented, recommend learn events instead of going sync. you.


Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -

java - Digest auth with Spring Security using javaconfig -