简体   繁体   English

网络工作者在Chrome打包计算器应用中解析原始输入

[英]Web Workers for Parsing Raw Input in Chrome Packaged Calculator App

I am currently working on a calculator that will run as a packaged (desktop) chrome app. 我目前正在使用将作为打包(桌面)Chrome应用程序运行的计算器。 I am using the math.js library to parse math input. 我正在使用math.js库来解析数学输入。 This is my old code: 这是我的旧代码:

evaluate.js: Evaluation.js:

var parser = math.parser();  
function evaluate(input){  
    $("#output").text(parser.eval(input));  
}

However, if the input is something unreasonable like 6234523412368492857483928! 但是,如果输入不合理,例如6234523412368492857483928! , the app just freezes, because it is trying to evaluate the input. ,该应用只是冻结,因为它正在尝试评估输入。 I know that math.js is still in beta so eventually there might be a fix (overflow errors), but I couldn't find any other library that parses raw input the way math.js does. 我知道math.js仍处于测试阶段,因此最终可能会解决(溢出错误),但是我找不到其他任何库可以像math.js一样解析原始输入。

To fix this, I am trying to fix this using web workers to run it asynchronously. 为了解决这个问题,我正在尝试使用网络工作者来解决此问题,以使其异步运行。 Here is the code that I have right now: 这是我现在拥有的代码:

main.js main.js

var evaluator = new Worker('evaluate.js');
evaluator.addEventListener('message', function(e){
    $("#output").text(e.data);
}, false);
function evaluate(input){
    evaluator.postMessage(input);
}

evaluate.js Evaluation.js

var parser = math.parser();
function mathEval(input){
    return parser.eval(input);
}
self.addEventListener('message', function(e){
    self.postMessage(mathEval(e.data));
});

However, this doesn't work when I run it. 但是,这在我运行时不起作用。 Also, I noticed that when I use web workers, it throws the error Uncaught ReferenceError: math is not defined - evaluate.js:1 , but it didn't throw this error with the old code. 另外,我注意到当我使用Web Worker时,它会引发错误Uncaught ReferenceError: math is not defined - evaluate.js:1 ,但是对于旧代码却没有引发此错误。

Questions: Why doesn't this code work to evaluate the input? 问题:为什么这段代码无法评估输入? Is it possible to use multiple workers to speed it up? 是否可以使用多个工作人员来加快速度? If I wanted to implement some sort of overflow error for when the worker takes more than 2 seconds, what would be the best way to go about doing it? 如果我想在工作者花费超过2秒的时间来实现某种溢出错误,那么做这件事的最佳方法是什么? Finally, is there a better way to do this? 最后,还有更好的方法吗?

Web Workers are run in totally separate context. Web Worker在完全独立的上下文中运行。 They don't have access to the objects from parent web page. 他们无权访问父网页上的对象。 If you want to use math.js you have to import it into the worker using importScript. 如果要使用math.js,则必须使用importScript将其导入到worker中。

I recommend to read Using Web Workers guide, part "Importing Scripts And Libraries" which describes how to do it, and how it works in detail. 我建议阅读“ 使用Web Workers”指南的“导入脚本和库”部分,其中介绍了如何进行操作以及其详细工作方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM