Skip to main content

Command Palette

Search for a command to run...

JS: async/await

Updated
1 min readView as Markdown

看到一篇 async/await 解釋得很清楚(又很短)的文章,也是面試被問過的內容,趕快翻中筆記重點一下XDDDD


async/await

async 函式 (function) 代表要讓這個函式作 asynchronous (非同步/異步) 處理,而且(!) 只會回傳 Promise 物件

await 關鍵字可用來等待函式完成某件事情、並 能接收函式回傳的Promise或其他結果

asyncawait 有幾個需要注意的用法如下:

  1. async 函式只會回傳 Promise 物件 ─ 即使不是在 async 函式裡面 return 一個 Promise 物件,如回傳JSON,這個JSON也會被包成 Promise 物件再丟出去。
  2. await 只能在 async 函式裡面使用。
  3. await 可接收 任何 函式回傳的結果 ─ 意思是沒有強制使用await關鍵字只能接收由 async 函式回傳的結果,也能接收普通函式回傳的東西。

如果 await 接收 async 函式回傳的結果,接收到的會是 Promise 物件; 但是,如果 await 接收普通函式回傳的結果,則接收到的東西型別會跟這個函式所回傳結果的型別相同。

意思是如果儲存某個 await 所接收的普通函式回傳結果,該函式回傳 string 會接收到 string;回傳 number 就會接收到 number,以此類推。

Error Handling

可以用 try...catch 來處理回傳的 Error 物件。

const app = async (url) => {
    try{
        console.log("Try to get the result...");
        const result = await fetch(url);
        console.log(result)            // 如果有成功的話
    } catch (err) {
        console.error(err.message);   // 失敗時候的錯誤處理
    }
}

app("a API endpoint");


原文作者提到他有發布跟asynchronous相關的系列文,蠻值得參考的!


References

More from this blog

Vite: vite-plugin-html的bugs和坑

因為工作要用Vite去生成一個mpa專案且根據頁面不同,動態生成不同 <title> 的HTML,所以就找了一個套件──vite-plugin-html,結果因為套件好像很久沒維護,隨著Vite升級又多了一些有的沒的bug,順手來記錄一下。 template delete 像我第一個就是遇到生成的時候template HTML也會被刪掉,後來看到issue上也有人反映,還好有好心人士解決這個問題,

Feb 26, 20261 min read4

Lun's Blog

82 posts

Notes for web development