目錄
在 JavaScript 的世界裡,非同步操作如fetch 和計時器是很常見的需求。
過去,我們只能在 async 函數內使用 await,這讓頂層程式碼的非同步操作顯得有些笨重。
然而,ES2022 引入了一個改變遊戲規則的新特性:Top-Level Await。
這能讓我們能在模組的頂層直接使用 await,簡化了程式碼結構,讓非同步操作更直觀。
什麼是 Top-Level Await?
Top-Level Await 允許我們在模組頂層使用 await,而不需要將其包裹在 async 函數中。
這使我們能更方便處理模組初始化過程中的非同步操作,如資料載入和設定組態等。
為什麼需要 Top-Level Await?
在介紹 Top-Level Await 前,讓我們先看看原本的程式碼是什麼樣子。
以下是一個典型的例子,我們需要等待一秒鐘後,再從 API 獲取資料:
const wait = milliseconds => {
return new Promise(resolve => {
setTimeout(() => {
resolve();
}, milliseconds);
});
}
const init = async () => {
await wait(1_000);
console.log("Waited 1 second");
const response = await fetch("https://jsdemo-3f387-default-rtdb.europe-west1.firebasedatabase.app/notifications/new.json");
const data = await response.json();
console.log(data);
}
init();
在這段程式碼中,我們需要定義一個 async 函數 init 來使用 await。
這在某些情況下顯得有些多餘,尤其是當我們只想在模組頂層執行非同步操作時。
使用 Top-Level Await 的程式碼
有了 Top-Level Await,我們可以直接在模組頂層使用 await,如下所示:
const wait = milliseconds => {
return new Promise(resolve => {
setTimeout(() => {
resolve();
}, milliseconds);
});
}
// 等待 1 秒鐘
await wait(1_000);
console.log("Waited 1 second");
// 從 API 獲取數據
const response = await fetch("https://jsdemo-3f387-default-rtdb.europe-west1.firebasedatabase.app/notifications/new.json");
const data = await response.json();
console.log(data);
這段程式碼顯得更為簡潔和直觀。現在,我們不需要將程式碼包裹在 async 函數中,
直接使用 await 來處理非同步操作。
Top-Level Await 的應用場景
模組初始化
Top-Level Await 非常適合用於模組初始化。
例如,可在模組載入時,等待組態檔案的讀取:
const config = await fetch('/config.json').then(response => response.json());
console.log('Config loaded:', config);
動態載入資料
我們可以在模組頂層動態載入必需的資料,這對於單頁應用(SPA)特別有用:
const userData = await fetch('/api/user').then(response => response.json());
console.log('User data:', userData);使用 Top-Level Await 的注意事項
- 僅限模組:Top-Level Await 只能在 ES 模組中使用。
如果你的檔案使用<script>標籤引入,請確保新增type="module"屬性。 - 模組依賴:使用 Top-Level Await 時,要注意模組的依賴關係。
如果一個模組依賴另一個模組且使用了 Top-Level Await,會導致依賴的模組也需要等待,
這可能會影響載入時間。
結論
Top-Level Await 是一個強大且便捷的新特性,讓我們可以在模組頂層更簡潔地處理非同步操作。
這不僅簡化了程式碼結構,也提高了程式碼的可讀性和維護性。
如果你還沒有嘗試過這個特性,不妨在你的下個項目中應用它,感受一下它帶來的便利吧!
額外資源
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await
探索更多來自 雖然沒準備什麼資料 的內容
訂閱即可透過電子郵件收到最新文章。