前端常見面試題之a(chǎn)sync/await和promise的區(qū)別
async
async函數(shù)定義
async函數(shù)是使用關鍵字聲明的函數(shù)。async 是“異步”的簡寫,所以應該很好理解 async 用于申明一個 function 是異步的。
作用
用于解決:異步程序產(chǎn)生的bug
####async函數(shù)的語法
async function name([param[, param[, ... param]]]) { statements }
參數(shù):name 函數(shù)名稱
? param 要傳遞給函數(shù)的參數(shù)的名稱
? statements 包含函數(shù)主體的表達式 ,可以使用await
返回值: 一個全新的promise,這個promise要么會通過一個由async函數(shù)返回的值被解決,要么會通過一個從async函數(shù)中拋出的(或其中沒有被捕獲到的)異常被拒絕
下面為async的具體使用實例:
async function foo(p) { console.log("foo run",p); return 1; } var res = foo(1); console.log(res);//{<fulfilled>: 1}
async函數(shù)一定會返回一個promise對象。如果一個async函數(shù)的返回值看起來不是promise,那么它將會被隱式地包裝在一個promise中。
例如,如下代碼:
async function foo() { //promise.[[promiseValue]] return 1 } //等價于 function foo() { return Promise.resolve(1) }//{<fulfilled>: 1}
下面是對async的一些補充:
- async 本身是一個語法糖—>語法糖:帶有一定功能的關鍵字
- 語法糖的作用:能夠減少代碼量、增加程序的可讀性,從而減少程序代碼出錯的機會
async 函數(shù)中 return 值如何接受
方式一
通過 promise.then-cb 形參獲取
async function foo(){ console.log(222222); return 123; } let res = foo(); res.then(data=>{ console.log(data);//123 })
方式二
第二種接受函數(shù)返回值的方式是 await
(async function (){ console.log('async run'); //第二種接受函數(shù)返回值的方式是 await let res = await foo(); console.log(res); })() async function foo(){ console.log('foo run'); return 123; } //res作用:接受 async foo函數(shù)返回值 是promise let res = foo();
await
await定義
await 的意思是等待,所以應該很好理解,await 等待某個操作完成。
作用
await關鍵字的作用 就是獲取 Promise中返回的內(nèi)容, 獲取的是Promise函數(shù)中resolve或者reject的值(await 作用是獲取promise.[[promiseValue]]的值)
關于await的注意點
- await 必須寫在 async 中
- await 后是一個promise實例對象
[[promiseValue]]
[[PromiseValue]]是個內(nèi)部變量,外部無法得到,只能在then中獲取。
[promiseValue]哪些能賦值
- async函數(shù)的return
- new promise 中 resolve實參
- then 中 return (catch finally 中的return)
- promise.reslove()實參 promise.reject()實參
三者的區(qū)別
- promise和 async/await都是解決異步編程的一種方式,但是async/await使得異步代碼看起來像同步代碼。
- 函數(shù)前面多了一個async關鍵字。await關鍵字只能用于async定于的函數(shù)內(nèi)。async函數(shù)會隱式地返回一個Promise,該promise的resolve值就是return的值。
為什么async/await更好?
使用async函數(shù)可以讓代碼簡潔很多,不需要像Promise一樣需要then,不需要寫匿名函數(shù)處理Promise的resolve的值,也不需要定義多余的data變量,還避免了嵌套代碼。
async/await 讓 try/catch可以同時處理同步和異步的錯誤。在下面的示例中,try/catch不能處理JSON.parse的錯誤,因為它在Promise中,我們需要使用.catch,這樣的錯誤會顯得代碼非常的冗余。
總結
到此這篇關于前端常見面試題之a(chǎn)sync/await和promise區(qū)別的文章就介紹到這了,更多相關async/await和promise區(qū)別內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Node登錄權限驗證token驗證實現(xiàn)的方法示例
這篇文章主要介紹了Node登錄權限驗證token驗證實現(xiàn)的方法示例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-05-05Node.js數(shù)據(jù)庫操作之連接MySQL數(shù)據(jù)庫(一)
前一陣在做項目的時候,需要通過nodejs連接到MySQL數(shù)據(jù)庫,于是簡單地學習了一下MySQL這個庫,分享一些學習心得給大家,希望對大家有幫助。下面這篇文章主要介紹了Node.js數(shù)據(jù)庫操作之連接MySQL數(shù)據(jù)庫的相關資料,需要的朋友可以參考下。2017-03-03koa+mongoose實現(xiàn)簡單增刪改查接口的示例代碼
這篇文章主要介紹了koa+mongoose實現(xiàn)簡單增刪改查接口的示例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-05-05