【问题标题】:Why to use while when it is always true?当它总是正确的时候为什么要使用while?
【发布时间】:2020-01-30 22:08:16
【问题描述】:

我在 redux-saga 中看到了大多数使用 while(true){} 的示例:

function* watcherSaga(){
  while (true) {
    yield something()
  }
}

我们不能简单地写吗?

function* watcherSaga(){
  yield something()
}

或者,有什么不同吗?

【问题讨论】:

  • 函数返回后,以及隐式,函数结束。
  • 为什么不在控制台试试呢?
  • this 上有一个github discussion
  • @guicy 不,它不会一样。如果没有while,该函数将只有yield 一个值。

标签: javascript ecmascript-6 generator redux-saga yield


【解决方案1】:

看看下面的例子。一个generator 永远不会“完成”,另一个生成器在第一个(也是唯一一个)yield 之后完成。

function something() {
  return Math.random();
}

function* watcherSaga1() {
  while (true) {
    yield something();
  }
}

function* watcherSaga2() {
  yield something();
}

const watcher1 = watcherSaga1();
const watcher2 = watcherSaga2();

console.log('watcher1: ', watcher1.next());
console.log('watcher1: ', watcher1.next());
console.log('watcher1: ', watcher1.next());

console.log('watcher2: ', watcher2.next());
console.log('watcher2: ', watcher2.next());
console.log('watcher2: ', watcher2.next());

【讨论】:

  • 谢谢。我明白了。但是我仍然对在 redux saga 中何时以及何时不使用而感到困惑。如果我理解它,如果需要多次观看动作,我需要 while true 吗?
【解决方案2】:

使用while 循环,生成器将永远继续产生值。没有,就只有一次。

当您需要某个序列(例如,7 的倍数)时,类似的函数可以轻松地向消费者提供这样的序列,从而对其需要的值数量施加自己的限制。

生成器提供了一种极其强大的代码结构方式,并且在某些情况下可以渗透到设计中。它们在媒体生成的上下文中特别有用,例如p5.js,其中有很多交互迭代。生成器提供了一种特别好的封装方式。

【讨论】:

  • @gulcy 回答扩展
  • @gulcy 就像其他任何东西一样,您确实需要需要语言功能才能易于理解。有时,产生遵循某种模式的无限序列值的函数很有用。
【解决方案3】:

Generators 返回一个Iterator

当你在迭代器上调用next()时,它会产生返回值,如果函数结束,它会产生一个未定义的值并完成。

检查下面的sn-p。希望这篇对你有所帮助。

function* watcherSaga() {
  var i = 0;
  while (true) {
    yield i++;
  }
}

const sagaIterator = watcherSaga();

console.log("**** with while() loop *****");
console.log(sagaIterator.next());
console.log(sagaIterator.next());
console.log(sagaIterator.next());
// You can keep calling sagaIterator.next() and it never gets "done" because of "while(true)"


function* watcherSagaWithoutWhile() {
  var i = 0;
  yield i++;
}

const sagaIteratorWİthoutWhite = watcherSagaWithoutWhile();


console.log("**** withOUT while() loop *****");
console.log(sagaIteratorWİthoutWhite.next());
console.log(sagaIteratorWİthoutWhite.next());
console.log(sagaIteratorWİthoutWhite.next());
// The second call to "next()" will return an "undefined" value and the generator gets done because the generator comes to the end

进一步阅读:https://basarat.gitbooks.io/typescript/docs/generators.html

【讨论】:

  • 这是否意味着当需要多次观看动作时我需要使用while循环?如果在观看后不需要采取行动,那么我不需要使用循环吗?我说的对吗?
  • 使用while(true) 循环,每当您在迭代器上调用next() 时,它都会产生一个值(意味着它永远不会结束)。如果没有循环,它只会产生一个值。
猜你喜欢
  • 1970-01-01
  • 2011-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-13
  • 1970-01-01
  • 2011-01-28
  • 1970-01-01
相关资源
最近更新 更多