Notes
Ajax 返回的顺序不确定
<head>
<title>Promise Intro</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
let user;
$.get('https://api.github.com/users',data=>{
console.log('fetched all users');
user = data[0].login;
});
$.get(`https://api.github.com/users/${user}/repos`,data => {
console.log('fetched user repos');
console.log(data);
})
</script>
</body>
嵌套写法,写在第一个请求的回调函数里,嵌套越多越混乱,会坠入回调地狱。
<script type="text/javascript">
let user;
$.get('https://api.github.com/users',data=>{
console.log('fetched all users');
user = data[0].login;
$.get(`https://api.github.com/users/${user}/repos`,data => {
console.log('fetched user repos');
console.log(data);
})
});
</script>
为解决回调不确定性和回调地狱,ES6提供了Promise承诺,比如:订单号。
用axios包来做下
.then()//事件监听成功之后执行 .catch()//返回错误信息
<head>
<title>Promise Intro</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.17.1/axios.min.js"></script>
</head>
<body>
<script type="text/javascript">
const usersPromise = axios.get('https://api.github.com/user');
//$('p').on('click',function(){}) 用.then()方法
usersPromise
.then(reponse =>{
username =reponse.data[0].login;
return axios.get(`https://api.github.com/users/${username}/repos`);
})
.then(reponse =>{
console.log(reponse.data);
})
.catch(err =>{
console.log(err);
})
</script>
</body>