Promise异步编程
promise 是提供异步编程的容器,包含异步代码。在得到异步结果时需要通过resolve 传递数据,(reslove对应then所指定的函数,也就是单个过程的异步回调)
以ajax请求封装为例
function ajax(url , success) {
var xhr = new XMLHttpRequest();
xhr.open("GET",url);
xhr.send();
xhr.onreadystatechange = function(){
if(xhr.status == 200 && xhr.readyState == 4){
//将请求结果作为实参传入成功回调
success(xhr.responseText);
}
}
}
//如果两个异步过程有先后顺序,则会出现这种嵌套情况
ajax("http://localhost:8080/api/getgoodList",function(res){
console.log(res);
ajax("http://192.168.210.35:3000/api/getlist",function(res){
console.log(res)
})
})
Promise形式
function ajax(url){
//promise容器包裹异步过程
return new Promise(resolve => {
var xhr = new XMLHttpRequest();
xhr.open("GET",url);
xhr.send();
xhr.onreadystatechange = function(){
if(xhr.status == 200 && xhr.readyState == 4){
//将异步结果使用resolve进行传递
resolve(xhr.responseText);
}
}
})
}
ajax("http://localhost:8080/api/getgoodList")
.then(res => {
console.log(JSON.parse(res))
})
.then(() => {
return ajax("http://192.168.210.35:3000/api/getlist")
})
.then(res => {
console.log(JSON.parse(res))
})
它解决了回调函数横向发展的问题,变成了纵向发展结构。