2

I have a lot of problems in my code because it is not synchronous. Here is an example of problem that i have in a chrome extension. This is my 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 is how i use getTranslation function in another function:

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

Is it something wrong there ?

13
  • Put the assignment of json_data inside of the callback function. Commented Aug 13, 2013 at 16:25
  • Ok but this is just a part of a function and didn`t solve my problem at all. After this I have an ajax request which use json_data. And i will get json_data undefined. Commented Aug 13, 2013 at 16:26
  • Put any code that needs to use json_data inside the callback as well, or inside a function that is called within the callback and receives json_data as an argument. If you put your Ajax call inside the callback, it will have access to json_data. Commented Aug 13, 2013 at 16:27
  • just edited my post. the last return is mandatory. I can`t use only callback Commented Aug 13, 2013 at 16:37
  • By the way, in your code, json_array is neither JSON, nor an array Commented Aug 13, 2013 at 16:37

2 Answers 2

0

Since you are using sync XHR, instead of ajax, you need to use a sync function to save data, instead of chrome.storage, which is async.

In the chrome.storage documentation, one of its features is

  • It's asynchronous with bulk read and write operations, and therefore faster than the blocking and serial localStorage API.

But being blocking (and sync) is what you want, so why don't you change to that API instead?

Or even better:

Convert your getTranslation() function to be async. You would only need to add a third parameter that would be a callback, and use it inside the nested callbacks (because if you do this, you can also use ajax instead of sync XHR).

That way is the right thing, but if you feel lazy and want an easier way, just do the former and change chrome.storage to localStorage and you are done.

EDIT: I see you have already changed you function to be async. And it seems it works correctly, but you updated your question and you seem to have problems grasping why this line does not work:

console.log(translated); //this is first and empty

You need to understand how event oriented programming works. You may think that the line

for (counter in toTranslateArray)

which contains getTranslation means "do translation of every counter inside this toTranslateArray", but actually means "fire a translation event for every counter inside this toTranslateArray".

That means when that console.log get executed this tasks have just been fired; it does not wait for it to be finished. Therefore translated is empty in that moment. And that's normal, is executed async.

I don't know what you need to do with the translated var once is finished, but I would try to fire a different event once the last item of the array gets processed.

But anyway, what you need is to do is to study some tutorial or something about event oriented programming so all this makes more sense to you.

About the localStorage, I don't know, I found out about that as an alternative in the chrome.storage documentation, I really don't know how to use it in your case.

But since javascript is event oriented, I really recommend you to learn events instead of just going back to sync. But is up to you.

Sign up to request clarification or add additional context in comments.

Comments

0

Create a custom event listener, where after you are done with stringifying json_data (done inside the the call back as suggested) it will then fire the event to do the ajax call. Go here to learn more about cusotm event JavaScript custom Event Listener

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.