Javascript Web Worker isn't getting message

82 views Asked by At

I have a web worker that's running a long-running calculation. I've split the calculation up to run in a chain of Promises, so several times per second, the thread has a chance to do something else before continuing with the calculation.

I want to be able to cancel the calculation by sending a message. Using Worker.terminate() kills the calculation, but doesn't free up the memory, and I'm running into browser crashes.

function calculate() {
    // case when no dice are being calculated
    if (!_diceList.length) {
        _finished = true;
        return Promise.resolve();
    }

    let promise = Promise.resolve();
    // create chain of promise calculations
    for (let i = 0; i < _totalPermutations; i += PERMUTATIONS_PER_BREAK) {
        promise = promise.then(() => {
            if (!_shouldContinue || _finished) {
                return;
            } else {
                reportStatus();
                _atBreak = false;
                calculateRecursive();
            }
        });
    }

    return promise;
}

// ...

function run(data) {
    setup(data.dice);

    calculate().then(() => {
        reportStatus();
    }).catch(() => true).then(() => {
        close(); 
    });
}

onmessage = function (e) {
    if (e.data === 'cancel') {
        _shouldContinue = false;
    } else {
        run(e.data);
    }
};

When I debug, I can see that the code that creates the Worker does send the 'cancel' message, but when I set a breakpoint in my onmessage in the Worker code, it never enters the function.

I know that JavaScript is single-threaded, but I thought the entire purpose of Promises was to simulate async behavior.

0

There are 0 answers