Js中異步處理的方案:
1.js的回調(diào)函數(shù)
2.Promise?then來(lái)實(shí)現(xiàn)
3.通過(guò)async和await來(lái)實(shí)現(xiàn)
Async修飾的方法特點(diǎn):
1.只有在async修飾的方法中才可以使用await
2.async修飾的方法會(huì)自動(dòng)返回一個(gè)Promise
Await特點(diǎn)
1.await關(guān)鍵字還有可以在async修飾的方法中使用
2.await后面必須要跟一個(gè)Promise
3.await會(huì)將異步函數(shù)轉(zhuǎn)換為同步等待
例子如下:
async?function?request1(){
????//request1()方法內(nèi)部的兩個(gè)await會(huì)串行執(zhí)行
????let?result1?=?await?axios("http://localhost:8888/aa")
????let?result2?=?await?axios("http://localhost:8888/bb")
}
async?function?request2(){
????//request2()方法內(nèi)部的兩個(gè)await會(huì)串行執(zhí)行
????let?result3?=?await?axios("http://localhost:8888/cc")
????let?result4?=?await?axios("http://localhost:8888/dd")
}
//request1()和request2()會(huì)并行執(zhí)行
request1();
request2();