3-1 async
/* async可以将一个普通函数的返回值变成promise */
async function go(){
return "p"
}
console.log(go());//promise
go().then(res=>{
console.log(res)//p
})
3-2 await
/*
1、await关键字只能在async函数使用,不能在普通函数中使用
2、await 相当于then,获取获取promise--resolve的结果
*/
async function show(){
console.log("start");
var p = await go();
console.log(p);
console.log("end")
}
async function go(){
return "mid"
}
show();
//start
mid
end
/* await 后面如果是promise会得到then的结果 */
async function show(){
console.log("start");
var p =await Promise.resolve("mid")
console.log(p);
console.log("end")
}
show();
//start
mid
end
/* await
1、相当于执行了promise的then函数
2、await后面不一定跟promise
3、await阻塞函数的执行,优先执行同步的代码再去之后await执行完毕之后的内容
*/
async function show(){
console.log("start");
await mid();
console.log("end")
}
async function mid(){
console.log("mid");
}
show();
console.log("a1");
//
start
mid
al
end
<!-- await会阻塞函数的执行,会优先执行await后面同步的代码,异步代码等待同步代码执行完毕之后再去执行 -->
<script>
async function a1(){
console.log("a1");
await a2();
console.log("end")
}
async function a2(){
console.log("a2");
}
a1();
console.log("a3");
Promise.resolve().then(()=>{
console.log("a4")
})
/*
a1
a2
a3
end
a4
*/
</script>
3-3 await http请求
/* await--async可以将异步变成同步代码 */
var url = 'http://47.108.197.28:3000/top/playlist';
async function show(){
var res = await $.ajax({url});
var id = res.playlists[0].id
var url02 = `http://47.108.197.28:3000/playlist/detail?id=${id}`;
var detail = await $.ajax({url:url02});
console.log(detail)
}
show();