繁体   English   中英

如何让redux派遣一个动作并返回一个承诺?

[英]How can I make redux dispatch an action as well as return a promise?

这是我在songAction.js中的功能

export function createSong(title, url, token) {

    axios.defaults.headers.common['Authorization'] = token

    return function (dispatch) {
        axios.post('http://localhost:8080/api/song/create', {
            title,
            link: url

        })
        .then((response) => {
            console.log('the response was', response)
            if(response.data.success){
                dispatch({type: "CREATE_SONG_FULFILLED", payload: response.data.song})
            } else {
                dispatch({type: "CREATE_SONG_REJECTED", payload: response.data})

            }
        })
        .catch((err) => {
            dispatch({type: "CREATE_SONG_REJECTED", payload: err})
        })
    }
}

我希望能够在调度后返回一个promise,这样我就可以在组件中使用这样的函数 -

 createSong(title, url, token)
   .then((result) =>{
        // do stuff with result 
     })

我知道我可以通过回调来使这个工作异步..但我想使用承诺的ES6功能。 我有点困惑,我怎么能这样做。

如果你想要完整的ES6,你应该使用async/await语法。 这消除了根本不需要处理承诺的需要。

export function createSong (title, url, token) {
  axios.defaults.headers.common['Authorization'] = token
  return async (dispatch) => {
    try {
      const response = await axios.post('http://localhost:8080/api/song/create', {
        title,
        link: url
      })
      console.log('the response was', response)
      if (response.data.success) {
        dispatch({type: 'CREATE_SONG_FULFILLED', payload: response.data.song})
      } else {
        dispatch({type: 'CREATE_SONG_REJECTED', payload: response.data})
      }
    } catch (err) {
      dispatch({type: 'CREATE_SONG_REJECTED', payload: err})
    }
  }
}

createSong返回的匿名函数标有新的async关键字。 这意味着匿名函数现在将返回隐式Promise。

async关键字还允许您在函数体中使用await ,以便awaitaxios.post的异步调用, axios.post其视为同步调用。

另一个优点是你可以回到使用普通的try / catch块。 这些实际上是在解决和拒绝幕后的隐含承诺,但它们以正常的方式行事。

因为匿名函数实际上返回一个Promise,在调用链的createSong(...) ,无论你在哪里调用createSong(...)函数,你也可以使用async / await语法......等等。 没有更多的回调,也没有更明确的Promise处理。

首先,您需要返回axios调用。

...
return function (dispatch) {
  return axios.post('http://localhost:8080/api/song/create', {
    title,
    link: url
  })
...

你的createSong函数正在返回另一个函数(所以它是一个curried函数)。

因此,

createSong(title, url, token)(dispatch)
.then(()=>{
  // something
})

看起来对我很有效。

我认为使用调度操作的返回值并不是非常“反应”的方法。

有一种更好的方法可以解决使用Redux Saga这样的“复杂”情况,例如这里

虽然,我过去以这种方式通过调度操作使用返回值:

export const updatePage = (id, batch) => {
  return dispatch => {
    dispatch({
      type: 'UPDATE_PAGE',
      payload: {
        id
      }
    })

    // Make an API call
    return requestUpdatePages(
      id, batch
    ).then(data => {
      // When API call is successful
      return dispatch({
        type: 'UPDATE_PAGE_SUCCESS',
        payload: {
          id,
          data
      })
    })
    .catch(error => {
      // When API call fails
      return dispatch({
        type: 'UPDATE_PAGE_FAIL',
        payload: {
          error,
          id
        },
        error: true
      })
    })
  }
}

// After dispatch is bound to action creators
// you can use it like this

handleClick(id) {
  const { updatePage } = this.props
  updatePage(id).then(action => {
    if(action.type === 'UPDATE_PAGE_SUCCESS') {
      console.log('Whee, page has been updated!', action.payload.data)
    } else {
      console.error('Something went wrong :-( ', action.payload.error)
    }
  })
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM