Since preemptive multitasking is not available in a browser, and JavaScript is inherently single threaded, how does a Redux Middleware like redux-saga handle infinite loops not designed for cooperative multitasking without triggering the long-running script dialog?
function* watchSaga() {
while (true) {
yield take(SOME_REQUEST);
// do something
}
}
Edit
My statement "not designed for cooperative multitasking" was wrong. A generator function's code is executed only until the first yield expression.
yield
is indeed the key, as it yields control, suspending the current generator function and returning a value to it.
A simple example:
function* counter() {
console.log('Running generator to first yield point');
var x = 0;
do {
console.log('About to increment and yield control');
yield ++x;
console.log('Running counter to next yield point - x is currently', x);
} while (true);
}
console.log('Instantiating generator');
var instance = counter();
console.log('Generator instantiated, calling for the first time');
console.log('The first entry in counter is', instance.next());
console.log('The second entry in counter is', instance.next());
console.log('The third entry in counter is', instance.next());
console.log('The program continues running');
This while is not an infinite loop, it's a generator https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators.
The yield keyword exits the function, but its state, including the last executed line, remains until the next time the function is called, when it restarts at the statement following the last executed line until it sees the yield keyword again.