0

I am using npm ws module (or actually the wrapper called isomorphic-ws) for websocket connection.

NPM Module: isomorphic-ws

I use it to receive some array data from a websocket++ server running on the same PC. This data is then processed and displayed as a series of charts.

Now the problem is that the handling itself takes a very long time. I use one message to calculate 16 charts and for each of them I need to calculate a lot of logarithms and other slow operations and all that in JS. Well, the whole refresh operation takes about 20 seconds.

Now I could actually live with that, but the problem is that when I get a new request it is processed after the whole message handler is finished. And if I get several requests in the meantime, all of them shall be processed as they came in. And so the requests are there queued and the current state gets more and more outdated as the time goes on...

I would like to have a way of detecting that there is another message waiting to be processed. If that is the case I could just stop the current handler at any time and start over... So when using npm ws, is there a way of telling that there is another message waiting in to be processed?

Thanks

Tomas Vancoillie
  • 3,463
  • 2
  • 29
  • 45
Aros
  • 199
  • 2
  • 14

1 Answers1

1

You need to create some sort of cancelable job wrapper. It's hard to give a concrete suggestion without seeing your code. But it could be something like this.

const processArray = array => {
  let canceled = false;

  const promise = new Promise((resolve, reject) => {
    // do something with the array
    for(let i = 0; i < array.length; i++) {
      // check on each iteration if the job has been canceled
      if(canceled) return reject({ reason: 'canceled' });
      doSomething(array[i])
    }
    resolve(result)
  })

  return {
    cancel: () => {
      cancel = true
    },
    promise
  }
}

const job = processArray([1, 2, 3, ...1000000]) // huge array

// handle the success
job.promise.then(result => console.log(result))

// Cancel the job
job.cancel()

I'm sure there are libraries to serve this exact purpose. But I just wanted to give a basic example of how it could be done.

Euroclydon37
  • 667
  • 7
  • 20