Async/Await是尚未正式公布的ES7标准新特性。简而言之,就是让你以同步方法的思维编写异步代码。对于前端,异步任务代码的编写经历了callback到现在流行的Promise,最终会进化为Async/Await。虽然这个特性尚未正式发布,但是利用babel polyfill我们已经可以在应用中使用它了。
####首先了解下async/await的使用场景及规则:
在使用 async/await 的时候最简单的场景就是当你需要执行一个耗时操作时或者必须为异步操作时就可以直接上,使用 async 来执行你的函数,在这个函数内部 使用 await 关键字来达到异步执行的最终目的:执行完毕(异步执行)了,可以运行下一行代码了!
- async 表示这是一个 async 函数,而 await 只能在这个函数里面使用。
- await 表示在这里等待 await 后面的操作执行完毕,再执行下一句代码。
- await 后面紧跟着的最好是一个耗时的操作或者是一个异步操作
var promiseCount = 0;
let thisPromiseCount = ++promiseCount;
let sleep = function (time) {
return new Promise( (resolve, reject) => {
setTimeout(function () {
resolve(thisPromiseCount);
}, time);
})
};
let Component = async () => {
// 在这里使用起来就像同步代码那样直观
console.time();
console.log('start');
let result = await sleep(3000); //sleep 为一个执行需要耗费 3s 的函数,并将await执行完的值赋值给result变量
console.timeEnd('end'); //约3S后执行
console.log(result); //1
};
Component();
####理解Async/Await方法后我们再看一下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更直观简洁。