async getCourseExperimentList(id) {
try {
var res = await ajax.myGet(
"/course/experiment/get?course_id=" + parseInt(id)
);
var data = [];
if (res.status == "OK") {
this.setState({ classNamw: res.course_experments[0].course_title });
for (var i = 0; i < res.course_experments.length; i++) {
//循环 每次添加一个 就校验下 有就不添加了 没有添加
var elem = {
key: i,
soft: i + 1,
end_time: res.course_experments[i].end_time,
experiment_id: res.course_experments[i].experiment_id,
max_training_times: res.course_experments[i].max_training_times,
start_time: res.course_experments[i].start_time,
experiment_title: res.course_experments[i].experiment_title,
status: res.course_experments[i].status,
ctrl: {
end_time: res.course_experments[i].end_time,
id: res.course_experments[i].id,
max_training_times: res.course_experments[i].max_training_times,
start_time: res.course_experments[i].start_time,
status: res.course_experments[i].status,
experiment_title: res.course_experments[i].experiment_title
}
};
data.push(elem);
// this.setState(datassss: elem);
}
this.setState({ dataSource: data });
if (this.state.dataSource.length == 2) {
// this.setState({ experimentId: [] }); //这个没起作用 本来就是空数组
// this.getExperimentList();
} else if (this.state.dataSource.length == 1) {
}
}
} catch (e) {
console.log(e);
}
}
一、async
async其实是ES7才有有的关键字,async的意思是异步,顾名思义是有关异步的操作
async用于声明一个函数是异步的。
通常情况下async、await都是跟随promise一起使用,因为async返回值都是一个promise对象,async适用于任何类型的函数上
二、基本使用
使用async其实很简单,只需要在函数前面加一个async即可,这个函数的返回值是一个promise
//用来声明一个函数是异步的
async function fn(){
return 123;
}
//返回值是一个promise
console.log(fn())
/*
Promise
__proto__: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: 123
*/
//可以通过.then拿到返回值
fn().then((data)=>{
console.log(data);//123
})
三、await
await关键字不能够单独使用,必须在async中进行使用
await等待异步执行返回结果后才会执行下面的代码,其实await就是阻止主函数的运行
function fn(){
return new Promise((resolve)=>{
setTimeout(()=>{
console.log(1111);
resolve()
},2000)
})
}
async function fn1(){
await fn();
setTimeout(()=>{
console.log(2222);
},1000)
}
fn1()
四、如何实现多个异步同步执行
function fn(){
return new Promise((resolve)=>{
setTimeout(()=>{
console.log(1111);
resolve()
},3000)
})
}
function fn1(){
return new Promise((resolve)=>{
setTimeout(()=>{
console.log(2222);
resolve()
},2000)
})
}
function fn2(){
return new Promise((resolve)=>{
setTimeout(()=>{
console.log(3333);
resolve()
},1000)
})
}
async function fn3(){
await fn();
await fn1();
await fn2();
}
fn3()
五、总结
async函数完全可以看作多个异步操作,包装成的一个 Promise 对象,而await命令就是内部then命令的语法糖。
因此如果需要实现多个异步同步执行必须每次await后都返回一个新的promise