方法一:
function createPromise(url){
//在Promise对象中封装好ajax请求然后返回出去
return new Promise(function(resolve,reject){
$.ajax({
url,
type:'get',
dataType:'json',
success(arr){
resolve(arr);
},
error(err){
reject(err);
}
});
});
}
Promise.all([//分别执行发送请求
createPromise('https://api.imjad.cn/cloudmusic/?type=comments&id=478963730'),
createPromise('https://api.imjad.cn/cloudmusic/?type=comments&id=28012031')
]).then(data=>{//两个请求都成功后执行,用循环将数据渲染到页面
console.log(data);
var [hotComments1,hotComments2]=["",""];
for(var i=0;i<10;i++){//只输出10条热评
hotComments1+=`<p>
用户昵称:<b>${data[0].hotComments[i].user.nickname}</b>,
用户评论:<b>${data[0].hotComments[i].content}</b>
</p>`;
hotComments2+=`<p>
用户昵称:<b>${data[1].hotComments[i].user.nickname}</b>,
用户评论:<b>${data[1].hotComments[i].content}</b>
</p>`;
}//将2份数据写到页面中
$("#div1").html(hotComments1+hotComments2);
},error=>console.log(`请求失败`));
运行结果:
方法二(改进):
jquery自身支持Promise
/*引入的jqeury版本不能太低,这里用的是3.4.1版*/
Promise.all([
$.ajax({url:'https://api.imjad.cn/cloudmusic/?type=comments&id=478963730',dataType:'json'}),
$.ajax({url:'https://api.imjad.cn/cloudmusic/?type=comments&id=28012031',dataType:'json'})
]).then(results=>{//两个请求都成功后执行,分别调用函数将数据渲染到页面
let [arr,json]=results;
console.log(results);
console.log(`成功了`);
hotcomments(arr);
hotcomments(json);
},error=>console.log(`失败了`));
function hotcomments(data){
for(var i=0;i<10;i++){//只输出10条热评
div1.innerHTML+=`<p>
用户昵称:<b>${data.hotComments[i].user.nickname}</b>,
用户评论:<b>${data.hotComments[i].content}</b>
</p>`;
}
}
运行结果:
成功拿到😄😄😄
使用的API参考自:网易云音乐API