为什么要用async await
- 封装的Ajax函数
function jqAjax(methods, url, data) {
return new Promise((resolve, reject) => {
$.ajax({
type: methods, //方法 GET POST PUT DELETE
url: url, //路径
contentType: 'application/json', // 作用: 向后台发送数据的格式必须为json字符串
data: data, //传给后台的数据 在调用这个函数时要把data转成json形式
async: 'true', //异步
success: function(res) { //成功
console.log(res);
resolve(res);
},
error: function(xhr, status, error) { //失败
console.log(error);
console.log(status);
reject(error);
}
})
})
}
- 调用Ajax函数
async function getSubject() {
let subject = await jqAjax("GET", "/subject/", JSON.stringify($("select").find("option:selected").val()))
getSubject();
- 为什么要用async await
- 是ES7提出的处理异步的最终方法
- 隐藏 Promise ,更易于理解
- 代码看起来更加简洁,少了很多 then 的嵌套。
这是不用async
function logFetch(url) {
return fetch(url)
.then(response => response.text())
.then(text => {
console.log(text);
}).catch(err => {
console.error('fetch failed', err);
});
}
这是用async
async function logFetch(url) {
try {
const response = await fetch(url);
console.log(await response.text());
}
catch (err) {
console.log('fetch failed', err);
}
}
直观的能感受到用async更便于阅读