gpt4 book ai didi

javascript - 回调函数 promise ajax

转载 作者:行者123 更新时间:2023-12-03 00:32:23 24 4
gpt4 key购买 nike

我在使用 Promise 回调显示来自 json 的信息时遇到问题。我已经显示了帖子,但无法显示每个帖子的评论。泰。

这是我的代码

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:''
}

})
}

})

最佳答案

如果您可以将 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>

以下是使用 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>

关于javascript - 回调函数 promise ajax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53802873/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com