链接redux-actions和redux-promise-middleware

Raj*_*rov 6 typescript redux redux-promise

我使用redux-actionsredux-promise-middleware来分派动作,以及TypeScript 2.1以获得async await支持.

这是一个使用redux-actions和的动作redux-promise-middleware

// create an async action
const fooAction = createAction('FOO', async () => {
  const { response } = await asyncFoo();
  return response;
});

// use async action
fooAction('123')
Run Code Online (Sandbox Code Playgroud)

这是动作链的一个例子,仅使用 redux-promise-middleware

const foo = () => dispatch => {
  return dispatch({
    type: 'TYPE',
    payload: new Promise()
  })
  .then(() => dispatch(bar()));
}
Run Code Online (Sandbox Code Playgroud)

如何链接redux-promise-middleware可以与redux-actions?一起使用?

Bal*_*zar 5

你必须记住,即使async await看起来是同步的,它在底层使用了 Promises,并且一个async函数总是会返回一个 Promise,无论你是否使用await

由于的第二个参数createAction是您的有效载荷创建者,因此没有什么可以阻止您使用生成的对象。

以下是基于您的初始代码的示例:

const fakeCall = () => new Promise(resolve => {
  setTimeout(() => resolve({ response: 'ok' }), 1E3)
})

const fooAction = createAction('FOO', async () => {
  const { response } = await fakeCall()
  return response
})

const foo = () => dispatch =>
  dispatch(fooAction())
    .then(() => dispatch(bar()))

// or

const foo = () => async dispatch => {
  await dispatch(fooAction())
  dispatch(bar())
}
Run Code Online (Sandbox Code Playgroud)