【发布时间】:2017-10-30 07:08:33
【问题描述】:
这是我在 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})
})
}
}
我希望能够在调度后返回一个承诺,这样我就可以在组件中使用这样的函数 -
createSong(title, url, token)
.then((result) =>{
// do stuff with result
})
我知道我可以传入一个回调来使这项工作异步。但我想使用 ES6 的 Promise 特性。我有点困惑如何做到这一点。
【问题讨论】:
-
function (dispatch) {和.then((response) => {都没有返回任何东西,所以这是一个开始的问题 -
刚从axios返回:
return axios.post('http://localhost:8080/api/song/create' ...
标签: javascript reactjs asynchronous ecmascript-6 promise