我是@teroneko/redux-saga-promise的开发者。它最初是从@adobe/redux-saga-promise派生出来的,但现在它已经完全改造为使用 @reduxjs/toolkit 中的 createAction 来支持 TypeScript。
为了与@ronen 的例子保持联系,这里是 TypeScript 的等价物。
创建Promise操作(创建者):
import { promiseActionFactory } from '@teroneko/redux-saga-promise'
export const fetchPostAction = promiseActionFactory<void>().create<{ id: string }>('FETCH_POST')
发送Promise操作(来自创建者):
// promiseMiddleware is required and must be placed before sagaMiddleware!
const store = createStore(rootReducer, {}, compose(applyMiddleware(promiseMiddleware, sagaMiddleware)))
await store.dispatch(fetchPostAction({ id: 'post-id' }))
要解决/拒绝Promise操作(来自 saga):
import { call, takeEvery } from 'redux-saga/effects'
import { implementPromiseAction } from '@teroneko/redux-saga-promise'
import { fetchPostAction } from './actions'
function * fetchPostSaga(action: typeof fetchPostAction.types.triggerAction) {
yield call(implementPromiseAction, action, function * () {
const { id } = action.payload
return yield call(apiCallToFetchPost, id)
})
// or for better TypeScript-support
yield call(fetchPostAction.sagas.implement, action, function * () {
const { id } = action.payload
return yield call(apiCallToFetchPost, id)
})
}
export function * rootSaga() {
yield takeEvery(fetchPostAction, fetchPostSaga);
}
发生什么了?
- Promise操作(创建者)被创建
- Promise操作(来自创建者)被创建并
- 发送到商店。
- 然后 promise 操作被转换为可等待的 promise 操作,其中将其延迟版本保存到元属性中。立即返回该操作并
- 传递给 saga 中间件。
- 现在可等待的Promise操作有资格在 implementPromiseAction 中使用,除了解决或拒绝保存在可等待Promise操作的元属性中的延迟Promise之外,别无其他。
有关更多功能和高级用例,请参阅自述文件。