关于js中如何避免回调地狱的问题
· 阅读需 5 分钟
很多js新人———嗯,也包括我,在js里第一次写东西的时候 ,接触到了axios,和很多萌新一样,我最早学会的js请求就只会最基本的回调函数:
axios.get('/api/data')
.then(response => {
// 处理数据
const data = response.data;
return anotherRequest(data.id); //调用数据
})
.then(secondResponse => {
// 嵌套层级增加......
})
.catch(error => {
// 错误处理
});
这样搞多了,复杂点的逻辑就会变成灾难性的回调地狱,加一个请求就得从头开始捋...
axios.get(`${API_URL}/users/1`)
.then(response => {
console.log('1. 获取用户信息:', response.data.name);
// 获取该用户的帖子
axios.get(`${API_URL}/posts?userId=${response.data.id}`)
.then(postsResponse => {
console.log('2. 获取用户帖子:', postsResponse.data.length);
// 获取第一个帖子的评论
axios.get(`${API_URL}/posts/${postsResponse.data[0].id}/comments`)
.then(commentsResponse => {
console.log('3. 获取帖子评论:', commentsResponse.data.length);
// 获取第一条评论的作者信息
axios.get(`${API_URL}/users/${commentsResponse.data[0].id}`)
.then(userResponse => {
console.log('4. 获取评论作者:', userResponse.data.name);
// 获取该作者的相册
axios.get(`${API_URL}/albums?userId=${userResponse.data.id}`)
.then(albumsResponse => {
console.log('5. 获取作者相册:', albumsResponse.data.length);
// 结果
console.log('6. 最终结果:', {
originalUser: response.data.name,
postCount: postsResponse.data.length,
commentCount: commentsResponse.data.length,
commentAuthor: userResponse.data.name,
albumCount: albumsResponse.data.length
});
})
.catch(err => console.error('获取相册失败:', err));
})
.catch(err => console.error('获取评论作者失败:', err));
})
.catch(err => console.error('获取评论失败:', err));
})
.catch(err => console.error('