在react+redux+axios项目中使用async/await
Async/Await
Async/Await是尚未正式公布的ES7标准新特性。简而言之,就是让你以同步方法的思维编写异步代码。对于前端,异步任务代码的编写经历了 callback
到现在流行的 Promise
,最终会进化为 Async/Await
。虽然这个特性尚未正式发布,但是利用babel polyfill我们已经可以在应用中使用它了。
http://www.tuicool.com/articles/B77zAbe
现在假设一个简单的React/Redux应用,我将引入 Async/Await
到其代码。
Actions
此例子中有一个创建新文章的 Action
,传统方法是利用 Promise
结合 Redux-thunk
中间件实现。
import axios from 'axios' export default function createPost (params) {
const success = (result) => {
dispatch({
type: 'CREATE_POST_SUCCESS',
payload: result
})
return result
} const fail = (err) => {
dispatch({
type: 'CREATE_POST_FAIL',
err
})
return err
} return dispatch => {
return axios.post('http://xxxxx', params)
.then(success)
.catch(fail)
}
}
现在将它改写为 async/await
的实现:
import axios from 'axios' export default function createPost (params) {
const success = (result) => {
dispatch({
type: 'CREATE_POST_SUCCESS',
payload: result
})
return result
} const fail = (err) => {
dispatch({
type: 'CREATE_POST_FAIL',
err
})
return err
} return async dispatch => {
try {
const result = await axios.post('http://xxxxx', params)
return success(result)
} catch (err) {
return fail(err)
}
}
}
async和await是成对使用的,特点是使代码看起来和同步代码类似。
Components
同样,在React组件中,也比较一下 Promise
和 Async/Await
的方法异同。
传统地使用 Promise
:
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { createPost } from '../actions/post' class PostEditForm extends Component {
constructor(props) {
super(props)
} contributePost = e => {
e.preventDefault() // .... get form values as params this.props.createPost(params)
.then(response => {
// show success message
})
.catch(err => {
// show error tips
})
} render () {
return (
<form onSubmit={this.contributePost}>
<input name="title"/>
<textarea name="content"/>
<button>Create</button>
</form>
)
}
} export default connect(null, dispatch => {
return {
createPost: params => dispatch(createPost(params))
}
})(PostEditForm)
如果使用 Async/Await
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { createPost } from '../actions/post' class PostEditForm extends Component {
constructor(props) {
super(props)
} async contributePost = e => {
e.preventDefault() // .... get form values as params try {
const result = await this.props.createPost(params)
// show success message
} catch (err) {
// show error tips
}
} render () {
return (
<form onSubmit={this.contributePost}>
<input name="title"/>
<textarea name="content"/>
<button>Create</button>
</form>
)
}
} export default connect(null, dispatch => {
return {
createPost: params => dispatch(createPost(params))
}
})(PostEditForm)
可以见得,两种模式, Async\Await
的更加直观和简洁,是未来的趋势。但是目前,还需要利用babel的 transform-async-to-module-method
插件来转换其成为浏览器支持的语法,虽然没有性能的提升,但对于代码编写体验要更好。
原文链接:http://blog.csdn.net/sinat_17775997/article/details/73526610
在react+redux+axios项目中使用async/await的更多相关文章
- wepy项目中使用async await
https://github.com/Tencent/wepy/wiki/wepy项目中使用async-await
- 在Silverlight中使用async/await
现在 async/await 大行其道,确实,有了 async/await ,异步编程真是简单多了,个人觉得 async/await 的出现,给开发者还来的方便,绝不亚于当年 linq 的出现. 但要 ...
- [C#] .NET4.0中使用4.5中的 async/await 功能实现异
好东西需要分享 原文出自:http://www.itnose.net/detail/6091186.html 在.NET Framework 4.5中添加了新的异步操作库,但是在.NET Framew ...
- 【TypeScript】如何在TypeScript中使用async/await,让你的代码更像C#。
[TypeScript]如何在TypeScript中使用async/await,让你的代码更像C#. async/await 提到这个东西,大家应该都很熟悉.最出名的可能就是C#中的,但也有其它语言也 ...
- 在现有代码中通过async/await实现并行
在现有代码中通过async/await实现并行 一项新技术或者一个新特性,只有你用它解决实际问题后,才能真正体会到它的魅力,真正理解它.也期待大家能够多分享解一些解决实际问题的内容. 在我们遭遇“黑色 ...
- [C#] .NET4.0中使用4.5中的 async/await 功能实现异步
在.NET Framework 4.5中添加了新的异步操作库,但是在.NET Framework 4.0中却无法使用.这时不免面临着抉择,到底是升级整个解决方案还是不使用呢? 如果你的软件还没发布出去 ...
- js循环中使用async/await踩过的坑
最近写koa的时候遇见需要在循环中使用async/await的情况,当然第一反应就是直接上forEach,然后就直接翻车了... 直接上代码: function handleSql(val) { re ...
- 理解ES7中的async/await
理解ES7中的async/await 优势是:就是解决多层异步回调的嵌套 从字面上理解 async/await, async是 "异步"的含义,await可以认为是 async w ...
- js中的async await
JavaScript 中的 async/await 是属于比较新的知识,在ES7中被提案在列,然而我们强大的babel粑粑已经对它进行列支持! 如果开发中使用了babel转码,那么就放心大胆的用吧. ...
随机推荐
- (zhuan) Some Talks about Dual Learning
研究|对偶学习:一种新的机器学习范式 this blog copy from: http://www.msra.cn/zh-cn/news/blogs/2016/12/dual-learning-2 ...
- Unity3D学习笔记(二十七):MVC框架下的背包系统(2)
Tools FileTools using System.Collections; using System.Collections.Generic; using UnityEngine; using ...
- kubectl基础支持
kubectl get deployment -n alpha kubectl get deployment *****-deployment -n alpha -o json kubectl rol ...
- C#调用cmd命令
using System.Diagnostics; public class CmdHelper { private static string CmdPath = @"C:\Windows ...
- ngui 适配iphone x
using UnityEngine; using System.Collections; [RequireComponent(typeof(UIPanel))]public class FixedUI ...
- js_计时器之setInterval
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- R语言 平滑连接
参考自 153分钟 使用平滑曲线,沿着X轴从左向右的顺序依次连接,可以使用spline样条函数线. x = 1:5 y = c(1,3,4,2.5,2) plot(x,y) sp = spline(x ...
- Spark强大的函数扩展功能
在数据分析领域中,没有人能预见所有的数据运算,以至于将它们都内置好,一切准备完好,用户只需要考虑用,万事大吉.扩展性是一个平台的生存之本,一个封闭的平台如何能够拥抱变化?在对数据进行分析时,无论是算法 ...
- 《剑指offer》第五十六题(数组中唯一只出现一次的数字)
// 面试题56(二):数组中唯一只出现一次的数字 // 题目:在一个数组中除了一个数字只出现一次之外,其他数字都出现了三次.请 // 找出那个吃出现一次的数字. #include <iostr ...
- Rest数据服务查询类-根据sql查询
Rest数据服务查询类 需要iserver data服务支持,但请求的时候,不依赖SuperMap js lib包. 构造函数:QueryById=function(p_params): p_para ...