How is multitasking achieved in Redux Middleware?

做~自己de王妃 提交于 2019-12-25 04:27:28

问题


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.


回答1:


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');



回答2:


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.



来源:https://stackoverflow.com/questions/41456031/how-is-multitasking-achieved-in-redux-middleware

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!