0

In our AngularJS App we have some really heavy operation which can take up to 10 seconds and can be called like 30 times. In order to not block the UI we want to make that function call in the background. But I cant figure out how to do that.

I tried using $q like a function:

this.$q(resolve => {
    resolve(someHeavyCalculation())
}).then(result => stuffWeHaveToDoAfterTheCall)

but this blocks our program.

I tried using $q.defered and setTimeout to make the call async

const defered = this.$q.defered()
setTimeout(() => {
    defered.resolve(someHeavyCalculation())
})
defered.promise.then(result => stuffWeHaveToDoAfterTheCall)

This worked but made every other call to $timeout last around 8 seconds, which breaks a lot of stuff (maybe because we call that function so often?).

The last thing I tried is hoping that $timeout would magically lift the call into the async world

this.$timeout(someHeavyCalculation).then(result => stuffWeHaveToDoAfterTheCall)

But this didn't work either.

So what is the correct way of turning this function into a promise?

danielspaniol
  • 2,228
  • 21
  • 38
  • 1
    https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers – str Nov 27 '17 at 16:41
  • Put the calculation in a web worker. Promises may help you to handle the asynchronous results, but they don't make anything run in background. – Bergi Nov 27 '17 at 18:47

0 Answers0