Redux中间件如何实现多任务处理?

问题描述:

由于抢占式多任务在浏览器中不可用,并且JavaScript本质上是单线程的,因此像redux-saga这样的Redux中间件如何在不触发长时间运行的脚本对话框的情况下处理并非为协作式多任务设计的无限循环?

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 
    }
}

修改

我的陈述不是为协作多任务设计的"是错误的.生成器函数的代码仅在第一个 yield 表达式之前执行.

My statement "not designed for cooperative multitasking" was wrong. A generator function's code is executed only until the first yield expression.

yield确实是关键,因为它 yields 控件

yield is indeed the key, as it yields control, suspending the current generator function and returning a value to it.

一个简单的例子:

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