【问题标题】:How is multitasking achieved in Redux Middleware?Redux 中间件是如何实现多任务处理的?
【发布时间】:2017-05-18 06:49:26
【问题描述】:

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

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

编辑

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

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2015-08-20
        • 2014-07-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-20
        • 1970-01-01
        • 2017-08-27
        相关资源
        最近更新 更多