1 Promise:对异步操作做了一个统一封装。
(1)
let p = new Promise((resolve,reject)=>{
$.ajax({
url:"data/a.json",
dataType:"json",
success(data){
resolve(data);
},
err(res){
reject(res)
}
})
});
p.then(
(data)=>{
console.log("成功");
console.log(data);
},
(res)=>{
console.log("失败");
console.log(res)
}
)
(2)Promise.all()
Promise.all([
$.ajax({"url":"data/a.json",dataType:"json"}),
$.ajax({"url":"data/b.json",dataType:"json"})
]).then(
(arr) =>{
console.log(arr);
},
(res)=>{
console.log("错了");
}
)
2 async,await (用同步的方式写异步代码)
async (show)=>{
let arr1 = await $.ajax({"url":"data/a.json",dataType:"json"})
let arr2 = await $.ajax({"url":"data/b.json",dataType:"json"})
console.log(arr1)
console.log(arr2)
}
show()
3 async,await在forEach中无法使用,这样会导致index顺序错误,针对这种场景可以将forEach换成for of,具体在项目中的代码如下:
for (let [index,value] of edit_res.data.info.condition.entries()) {
await data_.addFilter();
data_.filter_data_arr[index].name_en_cur = value.connection;
data_.filter_data_arr[index].condition_value_cur = value.daytime;
data_.filter_data_arr[index].condition_type_cur = value.type;
data_.filter_data_arr[index].condition_connection_con = value.value;
}