3

I have a list of functions in angular2/typescript app called as: f1, f2, f3, f4 etc... These functions can be executed in any order and all of them return void.

I am thinking run them in parallel but don't know how to do that with target ES5.

What is the best way to execute these functions?

thanks,

Austin

Mark van Straten
  • 9,287
  • 3
  • 38
  • 57
AustinTX
  • 1,322
  • 4
  • 21
  • 28

2 Answers2

3

In the browser the is only one UI thread. If you run code in the UI thread, there won't ever run anything in parallel.

If you want to run code in parallel, you can utilize web workers. A single web worker is also just one thread, if you want to run multiple functions in parallel, you need a new web worker instance for each.

I don't know the current state of web worker support.

For more details see for example

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • If this is true, how would you explain httpclient.get wherein if after I subscribe to it all of my code below the .subscribe() call will be executed before the httpclient.get finishes? – Artanis Zeratul Aug 05 '18 at 01:02
  • There is a difference between concurrently and parallel. When code execution is delegated to a callback (Promise), other code is executed until it completes or waits for a callback. This is what your code does while the get request waits for the response from the server. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop. There are also other good articles out there about this topic. – Günter Zöchbauer Aug 05 '18 at 04:49
  • thanks for your inputs. Is delegation possible by using Observable? Thanks. – Artanis Zeratul Aug 05 '18 at 06:45
  • @ArtanisZeratul sorry, don't know what that means – Günter Zöchbauer Aug 05 '18 at 19:17
2

Since all your functions are most likely promises and you don't care about the output or order, only that all are executed i would suggest using Promise.all():

Promise.all([f1(), f2(), f3(), f4(), f5()])
  .then(_ => console.log('all completed'));

This will let the promises run in background and only when all complete report back to you.

Mark van Straten
  • 9,287
  • 3
  • 38
  • 57