原生ajax
//创建异步对象
var xhr = new XMLHttpRequest();
//设置请求基本信息,并加上请求头
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.open('post', 'test.php' );
//发送请求
xhr.send('name=Lan&age=18');
xhr.onreadystatechange = function () {
// 这步为判断服务器是否正确响应
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.responseText);
}
};
jqueryAjax
var loginBtn = document.getElementsByTagName("button")[0];
loginBtn.onclick = function(){
ajax({
type:"post",
url:"test.php",
data:"name=lan&pwd=123456",
success:function(data){
console.log(data);
}
});
}
fetch
fetch('http://www.mozotech.cn/bangbang/index/user/login', {
method: 'post',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: new URLSearchParams([
["username", "Lan"],["password", "123456"]
]).toString()
})
.then(res => {
console.log(res);
return res.text();
})
.then(data => {
console.log(data);
})
Axios
axios({
method: 'post',
url: '/abc/login',
data: {
userName: 'Lan',
password: '123'
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
async await
promise 的链式调用
async function testAsync() {
return "hello async";
}
const result = testAsync();
console.log(result); // Promise { 'hello async' }
根据上面的代码结果可以看出async返回的是Promise对象。如果函数返回值是一个直接量,async函数会通过Promise.resolve()封装成Promise对象。
由于是Promise对象,我们只能通过then的链式调用来获取内部结果。而await用于等待async的返回结果,即Promise的最终结果。
- 如果await等到的不是一个Promise对象,那么await表达式等到的就是他的结果
- 如果await等到的是一个Promise对象,await会阻塞后面的代码,等待Promise的resolve结果,然后得到resolve的值,作为await的运算结果
await的优势在于处理then的链式调用
/**
* 传入参数n, 表示这个函数执行时间(毫秒)
* 执行结果是n+200,这个值用于下一步骤
*/
function takeLongTimeUsingChain(n) {
return new Promise(resolve => {
setTimeout(() => resolve(n + 200), 1000);
});
};
function step1(n) {
console.log(`step1 with ${n}`);
return takeLongTimeUsingChain(n);
}
function step2(n) {
console.log(`step2 with ${n}`);
return takeLongTimeUsingChain(n);
}
function step3(n) {
console.log(`step3 with ${n}`);
return takeLongTimeUsingChain(n);
}
如果使用Promise的then链式调用来实现:
function doIt() {
console.log("doIt");
const time1 = 300;
step1(time1)
.then(time2 => step1(time2))
.then(time3 => step2(time3))
.then(result=> {
console.log(`result is ${result}`)
console.log("doIt");
})
}
如果使用await方法:
async function doIt() {
console.log("doit begin");
const timer1 = 300;
const timer2 = await step1(timer1);
const timer3 = await step2(timer2);
const result = await step3(timer3);
console.log(`result is ${result}`);
console.log("doit end");
}