Redux中间件是如何实现多任务的?

How is multitasking achieved in Redux Middleware?

由于抢占式多任务处理在浏览器中不可用,并且 JavaScript 本质上是单线程的,像 redux-saga 这样的 Redux 中间件如何在不触发 long-运行 脚本对话框?

function* watchSaga() {
    while (true) {
        yield take(SOME_REQUEST);
        // do something 
    }
}

编辑

我的说法"not designed for cooperative multitasking"是错误的。生成器函数的代码只会执行到第一个 yield 表达式。

yield确实是关键,因为它产生控制,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');

这个 while 不是无限循环,它是一个生成器 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators

yield 关键字退出函数,但它的状态(包括最后执行的行)一直保持到下次调用该函数时,当它从最后执行的行之后的语句重新开始,直到它再次看到 yield 关键字.