如何在Redux Middleware中实现多任务处理?

时间:2017-01-04 04:06:09

标签: javascript multithreading multitasking redux-saga redux-middleware

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

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

修改

我的声明“不是为合作多任务而设计的”是错误的。生成器函数的代码仅在第一个 yield 表达式之前执行。

2 个答案:

答案 0 :(得分:2)

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

yield关键字退出该函数,但其​​状态(包括最后执行的行)一直保持到下次调用该函数时,它在最后执行的行之后的语句处重新启动,直到它再次看到yield关键字。 / p>

答案 1 :(得分:1)

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