[英]Callback functions promise ajax
i have a problem displying infromation from an json using promise callback .I already display posts , but i can't display comments for each post . 我在使用promise回调从json中显示信息时遇到问题。我已经显示了帖子,但是我无法显示每个帖子的评论。 Ty .
泰
Here is my code 这是我的代码
JS JS
var root = 'https://jsonplaceholder.typicode.com/posts'
$.ajax({
url: root,
method:'GET',
data:{
a:''
}
})
.done(function(post) {
for(i=0 ; i<10;i++){
document.write(JSON.stringify(post[i]))
document.write('<br>')
document.write('<br>')
document.write('<br>')
}
})
.done(function(comments){
for(j=0; j<10;j++){
$.ajax({
url: root +'/'+ j+'/comments',
method:'GET',
comments:{
b:''
}
})
}
})
If you can use ES8 syntax with async
await
, then proceed as follows: 如果可以将ES8语法与
async
await
,请按照以下步骤操作:
async function getHTML() { const root = 'https://jsonplaceholder.typicode.com/posts'; const response = await $.get(root); let html = ""; for (let i = 0; i < 10; i++) { html += JSON.stringify(response[i]) + "</br>"; comments = await $.get(root +'/' + i +'/comments'); for (const comment of comments) { html += JSON.stringify(comment) + "</br>"; } } return html; } getHTML().then(html => console.log(html), err => console.error(err));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Here is how you would do it with ES6 Promise.all
: 这是使用ES6
Promise.all
:
function getHTML() { var root = 'https://jsonplaceholder.typicode.com/posts'; return $.get(root).then(function (response) { var html = ""; var promises = []; // collect the requests for all comments for (var i = 0; i < 10; i++) { promises.push($.get(root +'/' + i +'/comments').promise()); } return Promise.all(promises).then(function (response2) { for (var i = 0; i < 10; i++) { html += JSON.stringify(response[i]) + "</br>"; for (var j = 0; j < response2.length; j++) { html += JSON.stringify(response2[j]) + "</br>"; } } return html; }); }); } getHTML().then((html) => console.log(html));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.