Javascript同步功能 - 铬扩展 [英] Javascript synchronous functions - chrome extension

查看:116
本文介绍了Javascript同步功能 - 铬扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码中有很多问题,因为它不是同步的。这是一个我在Chrome扩展中遇到的问题的例子。这是我的函数

pre $函数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,$ b $'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(jso n_parsed.translation);
});



$ b

这是我在另一个函数中使用getTranslation函数的方法:$ / $> b
$ b

  for(counter toTranslateArray)
{
getTranslation(toTranslateArray [counter],function(callback)
{
翻译+ =回调;
console.log(翻译); //这是第二个,工程
});
}
console.log(已翻译); //这是第一个空的
//代码取决于翻译

是不是有问题因为你使用的是同步XHR,而不是ajax,所以你需要使用同步功能来保存数据,而不是使用同步功能来保存数据的 chrome.storage ,这是异步的。



chrome.storage 文档,它的一个特性是



  • 它与批量读取和写入操作是异步的,因此比阻塞和串行 localStorage API快。


但是阻止(和同步)是你想要的,所以你为什么不改用这个API呢?



甚至更好:



转换您的 getTranslation()函数是异步的。你只需要添加第三个参数,这个参数就是一个回调函数,并且在嵌套的回调函数中使用它(因为如果你这样做的话,你也可以用ajax代替同步XHR)。

这就是正确的事情,但是如果你觉得懒惰,想要更简单的方法,只需做前者并更改 chrome.storage localStorage ,就完成了。


$ b 编辑:我看到你有已经改变你的功能是异步的。它看起来可以正常工作,但是你更新了你的问题,你似乎在抓住这条线路不工作的原因时遇到了问题:

 的console.log(翻译); //这是第一个和空的

您需要了解面向事件的编程是如何工作的。您可能认为该行

  for(counter toTranslateArray)

其中包含 getTranslation 表示将此内部的每个计数器翻译为toTranslateArray,但实际上意味着为此toTranslateArray中的每个计数器触发翻译事件



这意味着当控制台时。 log 执行这些任务刚被解雇;它不会等待它完成。因此翻译在那一刻是空的。这是正常的,执行异步。



我不知道你需要做什么用翻译 var一旦完成,但我会尝试发射一个不同的事件,一旦数组的最后一项得到处理。



但无论如何,你需要做的是学习一些教程或者关于面向事件的编程,所以这些对你来说更有意义。



关于 localStorage ,I不知道,我在 chrome.storage 文档中发现了这个问题,我真的不知道如何在你的案例中使用它。



但是因为javascript是面向事件的,所以我真的建议你学习事件,而不是回到同步。但取决于你。


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 ?

解决方案

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.

这篇关于Javascript同步功能 - 铬扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆