2

I am trying to simulate two asynchronous methods but am failing to figure out the concept behind it. I have this plunker where I am trying to calculate fibonacci number and at the same time do some additional work. The code required for the issue is located in src/app.ts The actions are as follows:

  1. I click Get Fibonacci
  2. Immediately after I click Click while Fibonacci loads a few times

I want the result to be like

loading status status status finished

but I get

loading finished status status status

because my promise locks UI and I am failing to understand how to make it not do so. If not looking at the example, the code for the promise looks like this:

var promise = new Promise((resolve, reject) =>
  resolve(this.fibonacci(num));
);
promise.then(result => {
  this.result = result;
  this.status += " finished";
});

What am I missing?

Andrius Naruševičius
  • 8,348
  • 7
  • 49
  • 78
  • Where can I find your js file in that plunker? – moon Dec 06 '17 at 10:02
  • @moon src/app.ts - also added this in the question – Andrius Naruševičius Dec 06 '17 at 10:04
  • 3
    You should do this calculation in separate thread with web workers. – dfsq Dec 06 '17 at 10:05
  • @dfsq I assumed keyword `async` is enough to make multithreading. My bad :( – Andrius Naruševičius Dec 06 '17 at 10:16
  • I think the fibonacci function use too much recursive calls, try to use a non-recursive version – Littlee Dec 06 '17 at 10:19
  • @Quentin it's not really a duplicate since it doesn't solve OP problem, however it explains promises. Webworker question would be more helpful I think. – dfsq Dec 06 '17 at 10:22
  • @AndriusNaruševičius Here is an example of the approach that will work better for you using web workers: https://plnkr.co/edit/BXRtjQSvcrpVj57bwoq2?p=preview – dfsq Dec 06 '17 at 10:24
  • `"I assumed keyword async is enough ..."` a common misconseption about JS and thinking that `await` pauses your code. Your code runs in one thread and one thread only so your code should not block. But when you call the `fetch` api (making http request) then how do you deal with the delay of return? This is why the `fetch` api and other native api's return a promise or use callback. It'll natively make the http request on another thread but immediately returns a promise to your script that you then can immediately return (non blocking). – HMR Dec 06 '17 at 11:27
  • @dfsq I suggest you put your comment as a separate answer as it does the job perfectly. Thank you very much! – Andrius Naruševičius Dec 06 '17 at 12:26
  • I would post it if the question was not closed as duplicate :) But nevermind, you are welcome! – dfsq Dec 06 '17 at 12:27

0 Answers0