Async+Await相較於promise代碼,優雅簡潔了不少,避免了.then嵌套回掉...promise
async function fun1(){ return "hello world"}function fun2() { console.log("我是後面的程序")}fun1().then(value=>{ console.log(value)})fun2();
//我是後面的程序
//hello world複製代碼
console.log(fun1())複製代碼
async 語法相對比較簡潔在函數前面添加async關鍵字,表示此函數爲一個異步函數,便是異步,就表示不會阻塞後面的程序,因此hello world後輸出,直接調用fun1()不會輸出hello world,經過打印輸出,咱們發現它返回的是一個promise對象,因此須要.then()回掉函數,輸出promise返回值。bash
let promise = new Promise((resolve, reject) => { setTimeout(() => { let flag=false if (flag) { resolve('success') } else { reject('failed') } }, 1000)})async function test() { let result = promise return result }test().then(response => { console.log(response) }).catch(error => { console.log(error)})複製代碼
當async有返回值,調用該函數時,內部會調用promise.resolve()把它轉化成一個對象返回,promis當內部拋出錯誤時,會調用promise.reject()返回錯誤的值,promise對象用catch方法進行錯誤捕獲。
異步
function promise(num){ return new Promise((resolve,reject)=>{ setTimeout(function(){ resolve(2*num) },3000) })}async function fun4(){ let result =await promise(20); console.log(result) console.log("我是後面的程序")}fun4()//3秒後先輸出40,再輸出我是後面的程序複製代碼
await 必須和async搭配使用,它等待的是一個promise對象執行完,並返回promise.resolve的值,當結果出現時再繼續執行後面的代碼,當等待結果發生異常如何處理呢?用try/catch,把await放到try裏來執行,用catch來處理異常。async
function promise(num){ return new Promise((resolve,reject)=>{ setTimeout(function(){ resolve(2*num) },3000) })}function num1(n){ return promise(n)}function num2(n){ return promise(n)}function num3(n){ return promise(n)}
//promise方式async function fun4(){ const time1 = 10; num1(time1) .then(time2 => num2(time2)) .then(time3 => num3(time3)) .then(result => { console.log(`result is ${result}`); }); // let result =await promise(20); // console.log(result) console.log("我是後面的程序")//這個函數中,我是後面的程序先執行,.then異步執行
}
//我是後面的程序,result is 80//async+await方式
async function fun4(){ const time1 = 10; const time2 = await num1(time1); const time3 = await num2(time2); const result = await num3(time3); console.log(`result is ${result}`); console.log("我是後面的程序")//這個函數中,我是後面的程序後執行,await先執行,獲得結果後再執行後面的代碼}fun4()//result is 80 我是後面的程序複製代碼
使用promise時都是用.then回掉處理返回的值,用await便避免了.then嵌套回掉,把異步用同步方式來實現了,沒有回掉調用感受。
函數
使用 async / await, 搭配 promise, 能夠經過編寫形似同步的代碼來處理異步流程, 提升代碼的簡潔性和可讀性。ui
Async Await 的優勢:spa
一、解決了回調地獄的問題
二、能夠添加返回值 return xxx;
三、能夠在代碼中添加try/catch捕獲錯誤3d