Javascript synchronous functions - chrome extension [duplicate]

会有一股神秘感。 提交于 2019-12-11 03:57:41

问题


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 ?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/18214286/javascript-synchronous-functions-chrome-extension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!