先上代码:
async componentDidMount() { let t = this; console.log(this.props.location); t.tree.getPandectView({}, t.state.page, this.state.pageSize); await t.getProjectId(); let searchParams = { order: 'asc', projectId: t.props.location.query.projectId || this.state.projectId, sort: 'contractType', contractClass:this.state.contractClass }; t.table.getBaseContracts(searchParams, t.state.page, this.state.pageSize) } getProjectId = async function(){ let t = this; await request({url:'/contractBase/pandectView',params:{page:t.state.page, rows:this.state.pageSize}}) .then(res=>{ console.log(res); this.setState({ projectId:2312 }) }) };
首先在组件的生命周期里定义async componentDidMount 这样,便可以在这个函数内使用await了,使用await的意思是:等t.getProjectId()这个函数执行完毕后,再继续往下执行.
在getProjectId 的函数中也同样运用了async 与await 只是请求完成的时候再继续往下执行,这样,原本是异步的函数操作通过es7的语法,便变为同步了,更多实践有待开发!