React/Redux应用使用Async/Await的方法
Async/Await是尚未正式公布的ES7标准新特性。简而言之,就是让你以同步方法的思维编写异步代码。对于前端,异步任务代码的编写经历了callback到现在流行的Promise,最终会进化为Async/Await。虽然这个特性尚未正式发布,但是利用babelpolyfill我们已经可以在应用中使用它了。
现在假设一个简单的React/Redux应用,我将引入Async/Await到其代码。
Actions
此例子中有一个创建新文章的Action,传统方法是利用Promise结合Redux-thunk中间件实现。
importaxiosfrom'axios'
exportdefaultfunctioncreatePost(params){
constsuccess=(result)=>{
dispatch({
type:'CREATE_POST_SUCCESS',
payload:result
})
returnresult
}
constfail=(err)=>{
dispatch({
type:'CREATE_POST_FAIL',
err
})
returnerr
}
returndispatch=>{
returnaxios.post('http://xxxxx',params)
.then(success)
.catch(fail)
}
}
现在将它改写为async/await的实现:
importaxiosfrom'axios'
exportdefaultfunctioncreatePost(params){
constsuccess=(result)=>{
dispatch({
type:'CREATE_POST_SUCCESS',
payload:result
})
returnresult
}
constfail=(err)=>{
dispatch({
type:'CREATE_POST_FAIL',
err
})
returnerr
}
returnasyncdispatch=>{
try{
constresult=awaitaxios.post('http://xxxxx',params)
returnsuccess(result)
}catch(err){
returnfail(err)
}
}
}
async和await是成对使用的,特点是使代码看起来和同步代码类似。
Components
同样,在React组件中,也比较一下Promise和Async/Await的方法异同。
传统地使用Promise:
importReact,{Component}from'react'
import{connect}from'react-redux'
import{createPost}from'../actions/post'
classPostEditFormextendsComponent{
constructor(props){
super(props)
}
contributePost=e=>{
e.preventDefault()
//....getformvaluesasparams
this.props.createPost(params)
.then(response=>{
//showsuccessmessage
})
.catch(err=>{
//showerrortips
})
}
render(){
return(
)
}
}
exportdefaultconnect(null,dispatch=>{
return{
createPost:params=>dispatch(createPost(params))
}
})(PostEditForm)
如果使用Async/Await
importReact,{Component}from'react'
import{connect}from'react-redux'
import{createPost}from'../actions/post'
classPostEditFormextendsComponent{
constructor(props){
super(props)
}
asynccontributePost=e=>{
e.preventDefault()
//....getformvaluesasparams
try{
constresult=awaitthis.props.createPost(params)
//showsuccessmessage
}catch(err){
//showerrortips
}
}
render(){
return(
)
}
}
exportdefaultconnect(null,dispatch=>{
return{
createPost:params=>dispatch(createPost(params))
}
})(PostEditForm)
可以见得,两种模式,Async\Await的更加直观和简洁,是未来的趋势。但是目前,还需要利用babel的transform-async-to-module-method插件来转换其成为浏览器支持的语法,虽然没有性能的提升,但对于代码编写体验要更好。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。