從 async 和 await 函數(shù)返回值說原理

什么是 async 和 await ?
async function helloAsync() {const result = await new Promise((resolve) =>setTimeout(() => resolve("Hello")));console.log(result); // Hello}helloAsync();
運行上面的代碼,函數(shù)將輸出 “Hello”,結(jié)果顯而易見,其中 await 將阻塞主線程,直到 promise 處理完成。
async
async 函數(shù)使我們能夠編寫基于 promise 的代碼,就像它是同步的一樣,但不會阻塞執(zhí)行線程。
通過事件循環(huán)異步運行,async 函數(shù)將始終返回一個值。
使用 async 簡單地將返回一個 promise,如果 apromise 沒有返回,會自動將它包裝在一個 promise 帶有它的值的 resolve 中。
await
await 運算符用于等待 promise ,它只能在 async 塊內(nèi)使用。關(guān)鍵字 await 使 JavaScript 等待直到 promise 返回結(jié)果。
需要注意的是,它只是讓 async 功能塊等待,而不是整個程序執(zhí)行。不能在常規(guī)函數(shù)中使用 await 關(guān)鍵字。
猜猜下面代碼片段的輸出。
async function helloAsync() {const result = await new Promise((resolve) =>setTimeout(() => resolve("Hello")));return result;}let asyncResult = helloAsync();console.log("helloAsync返回值:" + jsON.stringify(asyncResult));
根據(jù)上面的代碼,可能會認(rèn)為輸出 “Hello” ,對與錯要眼見為實,復(fù)制上面的代碼運行后,輸出為:asyncResult值:{},從輸出來看,變量 asyncResult 的值為{} 。
為什么會這樣?
因為異步函數(shù)總是返回一個承諾,而不是解決上面例子中的承諾,我們試圖從中提取價值。
如何解決?
由于 async 函數(shù)在上面的代碼片段中返回了一個 promise 對象,那么就可以使用 .then 方法獲取 async 函數(shù)的處理結(jié)果。
下面的代碼可以正常打印 async 函數(shù)的執(zhí)行結(jié)果。
async function helloAsync() {const result = await new Promise((resolve) =>setTimeout(() => resolve("Hello")));return result;}helloAsync().then((data) => {console.log("helloAsync返回值:" + jsON.stringify(data));});
更好的方法
使用 async 和 await 主要是想避免使用 promise 鏈或 .then 表達(dá)式,所以可以使用 async 和 await 本身來解決 promise,而不是使用 .then,下面代碼為推薦使用方式:
async function helloAsync() {const result = await new Promise((resolve) =>setTimeout(() => resolve("Hello")));return result;}async function testHelloAsync() {const output = await helloAsync();console.log("helloAsync返回值:" + JSON.stringify(output));}testHelloAsync();
總結(jié)
在實際開發(fā)項目中,是使用 Promises 還是 Async/Await 沒有好壞之分,取決于開發(fā)人員,我個人當(dāng)前是偏向使用 Promises 的。
學(xué)習(xí)更多技能
請點擊下方公眾號
![]()

