1

I'm developing a webapp in dart angular2. When I submit a form, the browser is stuck (the process time can be quite long). Is there a way to do it asynchronously ?

I have in my template :

 <form (ngSubmit)="onSubmit()"

and the corresponding method :

onSubmit() async {
   longProcess();
}

The method 'longProcess()' does not call a server. Only local computation.

Thanks for your help.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
matth3o
  • 3,229
  • 3
  • 20
  • 24

1 Answers1

1

longProcess() is very probably executed async already.

The problem is that the browser has only one thread. Even when something is processed async it runs in the same thread all your JavaScript runs. When one task is executed no other task can be active at the same time. If you could split up the big task into lots of smaller tasks and then call these smaller tasks async, then other waiting tasks can be done before the next of these smaller tasks is executed.

JavaScript can utilize WebWorkers to create additional. If code is run in such a WebWorker thread it doesn't block the main thread.

For more details about WebWorkers see Web workers in Angular 2 Dart

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • 1
    I'd add that one simple way to solve this is `await`-ing `window.animationFrame` in your work loop in `longProcess()`. I did this in http://filiph.github.io/markov/ (look for "Building the Markov chain in the browser"). This effectively splits the computation into the smaller tasks Gunther is talking about. – filiph Jun 02 '16 at 17:33
  • Thanks, I'll take a look at it... Actually I did the trick with the marvellous function `Isolate.spawn` :) – matth3o Jun 03 '16 at 08:39
  • And can you make an HTTP request in the spawned isolate? – Günter Zöchbauer Jun 03 '16 at 08:43
  • If you use Angular then you can utilize the WebWorker approach explained in the question linked to above (in my answer). – Günter Zöchbauer Jun 03 '16 at 08:44
  • I didn't try but I think Http requests can be made in the spawned isolate. At the end, the isolate is mapped to a webworker. I have the impression that the only advantage with the angular approach is that you can have webworkers for specific components. – matth3o Jun 03 '16 at 09:11
  • I think the main advantage of Angulars approach is that all your code runs in a webworker except only what is absolutely necessary to update the view, runs in the main thread. You don't have to care to make code run in an isolate and do the cumbersome communication between worker and ui thread. I haven't checked since a long time but isolates in the browser didn't support access to any browser API. If the isolate becomes a webworker, HTTP request should work though, but I don't have deep knowledge here. – Günter Zöchbauer Jun 03 '16 at 09:14