2

redux-saga チャンネルのドキュメントを調べていました。コードに遭遇した場所:

export function* saga() {
  const chan = yield call(countdown, value)
  try {    
    while (true) {
      let seconds = yield take(chan)
      console.log(`countdown: ${seconds}`)
    }
  } finally {
    if (yield cancelled()) {
      chan.close()
      console.log('countdown cancelled')
    }    
  }
}

ご覧のとおり、これは決して終了しない無限ループであるため、break または throw と例外を呼び出す必要があります。しかし、上記の例では、どれも当てはまりません。上記のコードまたは呼び出し元の関数内でスローされるブレークまたは例外はありません。上記の無限ループが終了し、finally ブロックに到達するにはどうすればよいでしょうか?

参照: http://yelouafi.github.io/redux-saga/docs/advanced/Channels.html

4

3 に答える 3

2

関数の内容を見ると、が 0 以下の場合に特別なアクションが発生countdownすることがわかります。ENDsecs

import { eventChannel, END } from 'redux-saga'

function countdown(secs) {
  return eventChannel(emitter => {
      const iv = setInterval(() => {
        secs -= 1
        if (secs > 0) {
          emitter(secs)
        } else {
          // this causes the channel to close
          emitter(END)
          clearInterval(iv)
        }
      }, 1000);
      // The subscriber must return an unsubscribe function
      return () => {
        clearInterval(iv)
      }
    }
  )
}

(上記のスニペットはhttp://yelouafi.github.io/redux-saga/docs/advanced/Channels.htmlからのものです)

ENDアクションは、次のドキュメントに記載されていますtake(pattern):
http://yelouafi.github.io/redux-saga/docs/api/index.html#takepattern

于 2016-08-12T17:19:11.723 に答える
1

この行は、いくつかの呼び出しで例外をスローするようです

yield take(chan)

自己の戻り値によって生成されるため、無限ループはまったくありません。

更新: yield の仕組みの詳細については、https ://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/yield を参照してください。

于 2016-07-31T07:41:32.893 に答える