AngularJS 和网络工作者 [英] AngularJS and web workers
问题描述
angularJS 如何使用 web worker 在后台运行进程?这样做有什么我应该遵循的模式吗?
How can angularJS use web workers to run processes in the background? Is there any pattern I should follow on doing this?
目前,我使用的服务在单独的 Web Worker 中具有该模型.此服务实现如下方法:
Currently, I am using a service that has the model in a separate web worker. This service implements methods like:
ClientsFacade.calculateDebt(client1); //Just an example..
在实现中,此方法将带有数据的消息发送给工作线程.这让我可以抽象出它是在一个单独的线程中执行的事实,我还可以提供一个实现来查询服务器,甚至是在同一线程中执行此操作的服务器.
In the implementation, this method sends a message to the worker with the data. This allows me to abstract the fact that it is being performed in a separate thread and I could also provide an implementation that queries against a server or even one that does this action in the same thread.
由于我是 javascript 新手,而且我只是在回收我从其他平台获得的知识,所以我想知道这是否是您会做的事情,或者我正在使用的 Angular 提供了一种这样做的方法.这也引入了我的架构的变化,因为工作人员必须明确地将更改推送到控制器,然后更新其值,然后这会反映在视图中,我是否过度设计了这个?网络工作者通过不允许我共享内存等来保护"我免于搞砸,这有点令人沮丧.
Since I'm new to javascript and I'm just recycling knowledge I have from other platforms I wonder if this is something you would do or perhaps Angular which is what I am using, offers a sort of way of doing this. Also this introduces a change in my architecture since the worker must explicitly push changes to the controller, which then updates its values and then this is reflected in the view, am I over engineering this? It's a bit frustrating that web workers "protect" me so much from screwing up by not allowing me to share memory etc.
推荐答案
与 Web 工作者的通信通过消息传递机制进行.拦截这些消息发生在回调中.在 AngularJS 中,放置 Web Worker 的最佳位置是在服务中,正如您所指出的.解决这个问题的最好方法是使用 Promise,Angular 可以很好地使用它.
Communication with Web workers happens through a messaging mechanism. Intercepting these messages happens in a call back. In AngularJS, the best location to put a web worker is in a service as you duly noted. The best way to deal with this is to use promises, which Angular works amazingly with.
这是一个 service
var app = angular.module("myApp",[]);
app.factory("HelloWorldService",['$q',function($q){
var worker = new Worker('doWork.js');
var defer = $q.defer();
worker.addEventListener('message', function(e) {
console.log('Worker said: ', e.data);
defer.resolve(e.data);
}, false);
return {
doWork : function(myData){
defer = $q.defer();
worker.postMessage(myData); // Send data to our worker.
return defer.promise;
}
};
});
现在任何访问 Hello World 服务的外部实体都不需要关心 HelloWorldService
的实现细节 - HelloWorldService
可能可以通过 web worker<处理数据/code>,通过
http
或在那里进行处理.
Now whatever external entity that accesses Hello World service need not care about the implementation details of HelloWorldService
- HelloWorldService
could probably process the data over a web worker
, over http
or do the processing right there.
希望这是有道理的.
这篇关于AngularJS 和网络工作者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!