1-什么是promise
监听器
怎么样实现一个promise new
promise函数中传递两个参数
resolve -->处理成功 then去触发resolve
reject -->处理失败 catch去触发 reject
这两个函数不会马上执行
then和catch只会触发一个
promise其实就是为了方便程序员阅读代码
本质上就是为了替代回掉函数的
2-简写:
var p=Promise.resolve(100)
var r=Promise.reject(200)
console.log(p)
r.catch(err=>{
console.log(err);
})
3-回调地狱:
两段http请求存在依赖,嵌套关系的时候就会造成回掉地狱
<script>
var url = `http://47.108.197.28:3000/top/playlist`;
$.ajax({
url,
success:res=>{
var {name,id,coverImgUrl} = res.playlists[0];
$("#name").html(name)
$("img").attr("src",coverImgUrl)
/* 获取歌曲详情相关的数据 */
var url = `http://47.108.197.28:3000/playlist/detail?id=${id}`;
$.ajax({
url,
success:res=>{
console.log(res.playlist.description)
var detail = res.playlist.description;
$("#detail").html(detail)
}
})
}
})
</script>
<script src="http/callhttp.js"></script>
function http({
url,
success
}){
$.ajax({
url,
success:res=>{
success(res)
}
})
}
<script>
/* promise其实就是为了方便程序员阅读代码
本质上就是为了替代回掉函数的
*/
var url = 'http://47.108.197.28:3000/top/playlist';
// http(url).then(res=>{
// console.log(res)
// }).then()
http({
url,
success:res=>{
console.log(res)
http({
url:`http://47.108.197.28:3000/playlist/detail?id=6827562995`,
success:res=>{
console.log(res)
}
})
}
})
</script>
<script src="http/http.js"></script>
/* 通过promise封装http请求 */
function http(url){
return new Promise((resolve,reject)=>{
$.ajax({
url,
success:res=>{
resolve(res)
},
error:err=>{
reject(err);
}
})
})
}
<script>
/* promise其实就是为了方便程序员阅读代码
本质上就是为了替代回掉函数的
*/
var url = 'http://47.108.197.28:3000/top/playlist';
http(url).then(res=>{
var id = res.playlists[0].id
return id;
}).then(id=>{
var url = `http://47.108.197.28:3000/playlist/detail?id=${id}`;
http(url).then(res=>{
console.log(res)
})
})
</script>
4-forEach 不支持异步循环
<script>
var t1 = new Promise((resolve)=>{
setTimeout(()=>{
resolve("100")
},1000)
})
var t2 = new Promise((resolve)=>{
setTimeout(()=>{
resolve("200")
},1000)
})
var t3 = new Promise((resolve)=>{
setTimeout(()=>{
resolve("300")
},1000)
})
var arr = [t1,t2,t3];
arr.forEach(async item=>{
var res = await item;
console.log(res)
})
</script>