並行執行任務
yield
陳述非常適合在線性樣式中表示非同步控制流,但我們也需要並行進行。我們不能寫
// wrong, effects will be executed in sequence
const users = yield call(fetch, '/users')
const repos = yield call(fetch, '/repos')
因為第 2 個效果只會在第一個呼叫解析後才會執行。反之,我們必須寫
import { all, call } from 'redux-saga/effects'
// correct, effects will get executed in parallel
const [users, repos] = yield all([
call(fetch, '/users'),
call(fetch, '/repos')
])
當我們讓出一系列效果時,產生器會被阻擋,直到所有效果都解析完畢,或一旦其中一個遭到拒絕時 (就像 Promise.all
的行為一樣)。