async函數返回的是一個Promise,可以進行Promise的相關操做,函數內部返回的結果會成爲then方法回調函數的參數promise
async function asyncfunc(){ return "這是一個async函數" } asyncfunc() asyncfunc().then(function(info){console.log(info)})
當函數執行中遇到await,需等異步操做完成,纔會執行後面的代碼異步
async function asyncfunc() { let now = new Date().getTime(); await new Promise((resolve, reject) => { setTimeout(() => { resolve() }, 2000) }) console.log(new Date().getTime() - now) }
函數內部錯處,返回的promise狀態爲rejectedasync
async function asyncfunc(){ console.log(err) }
async函數返回的Promise只有函數內部中await後的異步事件執行完後,纔會改變,除非中途return或者出錯函數
(async function() { await new Promise((resolve, reject) => { console.log("第一個await") resolve() }) await new Promise((resolve, reject) => { console.log("第二個await") resolve() }) await new Promise((resolve, reject) => { console.log("第三個await") resolve() }) })().then(info=>{console.log("觸發then")})
(async function() { await new Promise((resolve, reject) => { console.log("第一個await") resolve() }) return "執行return" await new Promise((resolve, reject) => { console.log("第二個await") resolve() }) await new Promise((resolve, reject) => { console.log("第三個await") resolve() }) })().then(info=>{console.log("觸發then")})
(async function() { await new Promise((resolve, reject) => { console.log("第一個await") resolve() }) throw new Error("出錯了") await new Promise((resolve, reject) => { console.log("第二個await") resolve() }) await new Promise((resolve, reject) => { console.log("第三個await") resolve() }) })()
await後的Promise狀態變爲rejected時,會被catch接收到spa
(async function() { await new Promise((resolve, reject) => { reject("狀態變爲rejected") }) })().catch(info => { console.log(info) })
任意一個await後的Promise函數變爲rejecte,async函數的執行就會中斷,若想繼續執行,可以使用try{}catch(e){}捕獲3d
(async function() { await new Promise((resolve, reject) => { reject("狀態變爲rejected") }) await new Promise((resolve, reject) => { console.log("第二個await") resolve() }) })().catch(info => { console.log(info) })
(async function() { try { await new Promise((resolve, reject) => { reject("狀態變爲rejected") }) } catch (err) { console.log("捕獲" + err) } await new Promise((resolve, reject) => { console.log("第二個await") resolve() }) })().catch(info => { console.log(info) })
另外一種方法是將await後面的Promise添加catchcode
(async function() { await new Promise((resolve, reject) => { reject("狀態變爲rejected") }).catch(info => { console.log("捕獲" + info) }) await new Promise((resolve, reject) => { console.log("第二個await") resolve() }) })().catch(info => { console.log(info) })