angular2 work in background thread with custom ser

2019-07-25 10:09发布

问题:

How could I achieve this: I have some potentially long computation (eg. huge JSON to parse as http resp.) and want to do it in a non-blocking way.

I tried to adopt multithread.js lib to do the background work using web worker. This lib requires JSON serializable objects to pass to the execution function which is not aware of closures, DOM or any other globals. eg. MT.process(longRunningJob, doneCallback)(jsonSerializableArgForBGJob). But this lib is rather old (3 years ago last commit). Are there any better alternatives more suitable for angular2? I need to target widest range of browsers including older ones (except IE/Edge) so service worker or lib using it probably is not an option.

For serialization I found this cerialize lib to serialize custom objects by decorating their props. That could actually work but it adds quite a lot of code and seems error prone. My other concern is that I use inheritance and polymorphism and not sure if the lib is ready for such UC. One would expect mechanism known from Java: Serializable interface and overriden serialize/deserialize methods. Is there a way to accomplish this in typescript/angular2?

回答1:

JavaScript is single threaded and asynchronous as long as your code is asynchronous. This means that if your code is blocking (long running loop) then you're blocking other code to be executed.

RxJS doesn't use WebWorkers so everything you do is blocking the execution thread.

I think if you want to process data in a non blocking way there's currently no other way than implementing it by yourself with WebWorkers.

Also, note that asynchronous doesn't mean parallel.



回答2:

Take a look at the vkThread plugin or on its Angular version ng-vkThread

With this plugin you can download data directly in a thread, process and return result in UI.

doc and live demo for vkThread

doc and live demo for ng-vkThread

Please let me know if you have any questions.