虽然知道是延迟对象和回调,但是自己在开发中很少用到,希望可以举几个例子说明一下
$.ajax(
url:'../test/api1'
...
success: function(res1){
$.ajax(
url: '../test/api2' + res1.id
...
success: function(res2){
$.ajax(
url: '../test/api3' + res2.title
...
success: function(res3){
// some code ...
console.log(res3.content)
}
)
}
)
}
)
像这样的异步请求(还没写失败的回调), 形成callback hell, 代码成了一金字塔, 用deferred,或者叫promise的话,可以这样写
$.ajax(
url:'../test/api1'
...
).then(
function(res1) {
return $.ajax(
url: '../test/api2'+ res1.id
)
}
).then(
function(res2){
return $.ajax{
url: '../test/api3' +res2.title
}
}
).then(
function(res3) {
console.log(res3.content)
}
).catch(
err => {console.log(err)}
)
这样子写至少能好看很多, 如果then()里的函数如果采用es6箭头函数的写法, 就更简洁了.
我这里有以前写的一个完整例子, 可以看下, 复制下来就能跑.
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src='https://cdn.bootcss.com/jquery/1.8.0/jquery-1.8.0.min.js' type='text/javascript'> </script>
</head>
<body>
<div class="result"></div>
<button type="" id="btn">测试</button>
</body>
<script>
$('#btn').on('click', function(){
$.get('https://cnodejs.org/api/v1/topics').then(
function(res){
console.log(new Date().getTime())
// console.log(res)
return $.get('https://cnodejs.org/api/v1/user/'+res.data[0].author.loginname)
}).then(
function(res){
console.log(new Date().getTime())
console.log(res)
return $.get('https://cnodejs.org/api/v1/topic/'+ res.data.recent_topics[0].id)
}
).then(function(res){
console.log(new Date().getTime())
console.log(res)
$('.result').html(res.data.content)
}).fail(
function(err){
console.log(err)
})
})
</script>
</html>
10 回答11.3k 阅读
5 回答4.9k 阅读✓ 已解决
4 回答3.2k 阅读✓ 已解决
2 回答2.8k 阅读✓ 已解决
3 回答2.4k 阅读✓ 已解决
3 回答2.2k 阅读✓ 已解决
2 回答2.6k 阅读✓ 已解决
当调多个api,依赖的时候。