js 的異步回調
async await 是基於 Promise 實現的 他不能用於普通的回調函數
async 和 Promise 一樣是非阻塞的
async 使異步代碼看起來更像同步
makeRequest()
console.log('up')
function MakeRequest (){
test().then((d)=>{
console.log(d.data)
})
}
console.log('down')
顯示的順序是 up down 請求 請求有延時 無論在哪裏執行請求都會在 最後執行打印
async 異步調用
console.log('up')
async function MakeRequest (){
console.log('beforeDown')
await test().then((d)=>{
console.log(d.data)
})
console.log('down')
await bean().then((d)=>{
console.log(d.data)
})
}
console.log('Footerdown')
MakeRequest ()
顯示的順序是 up Footerdown beforeDown 請求 down 請求 在async 裏面按自上而下 同步執行
錯誤處理
try catch 無法攔截到 普通請求 JSON.parse 轉化的錯誤 加上 async await 就可以攔截
async function MakeRequest (){
try{
await test().then((d)=>{
console.log(JSON.parse(d))
})
/* .catch((e)=>{
console.log(e)
})*/
}.catch(e){
console.log(e)
}
}
MakeRequest ()
使用async await 的好處
使用async 不需要那麼多的箭頭函數,可以向調試同步代碼一樣跳過await
語法promise 在then裏面 添加斷點調試器 不會調到下一個then裏面
因爲他會跳過異步代碼
async function MakeRequest(){
console.log("up")
var d=await test()
console.log(d.data)
var dd=await bean()
console.log(dd.data)
console.log("down")
}
MakeRequest()
執行順序 up 請求 請求 down 執行順序按照從上到下執行
Promise 的使用
console.log("before")
new Promise((resolve)=>{
console.log("upup")
test().then((d)=>{
console.log("up1")
resolve(d.data)
console.log("up2")
})
console.log("beforedown")
}).then((d)=>{
console.log(data1)
console.log(d)
console.log(data2)
})
console.log("down")
執行順序 beforeup upup brforedown down up1 up2 data1 resolve返回值 data2 異步請求之外自上而下執行