异步请求
背景:
异步请求,为了优化用户体验,而诞生。
ajax
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","test1.txt",true);
xmlhttp.send();
- 界面用户体验改善,局部刷新
- 每次都需要重复写XMLHttpRequest相关代码
calback
function sum(a,b,cb){
const sum = a+b;
if(cb && typeof cb === 'function'){
cb(sum)
}
}
sum(1,2,function(parm){
console.log(parm);
})
- 依赖于之前业务逻辑,并非真正的异步,
var request = $.ajax({
url: "script.php",
method: "POST",
data: { id : menuId },
dataType: "html"
});
request.done(function( msg ) {
$( "#log" ).html( msg );
});
request.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
- 进行了封装,减少了XMLHttpRequest相关代码
fetch
fetch("http://xxxx").then(res => {
console.log("fecth res....");
}).catch(error => {
console.log("fetch error");
})
promise
new Promise().then(res => {
console.log("promise res....");
}).catch(error => {
console.log("promise error");
})
- 代码返回结果处理,拉平,编写上体验更好,
axios 增强版promise
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
//同时发出多个请求
function getUserAccount() {
return axios.get('/user/12345');
}
function getUserPermissions() {
return axios.get('/user/12345/permissions');
}
axios.all([getUserAccount(), getUserPermissions()])
.then(axios.spread(function (acct, perms) {
// 两个请求现在都执行完成
}));
es6 async/await
async function getUserName(){
const userName = await queryUserName();
return userName;
}
e6 yield
const getUser = function* getUserName(){
yield "zhangsan";
yield "xiaoming"
}
- 多个请求之间,把异步代码修改为同步,等待
Rxjs
const foo = new Observable(subscriber => {
console.log('Hello');
subscriber.next(42);
});
foo.subscribe(x => {
console.log(x);
});