20個(gè)你不得不知道的JS async/await實(shí)用技巧
20個(gè)你不得不知道的Js async/await用法
1. 基礎(chǔ)用法
async
函數(shù)返回一個(gè)Promise
,而await
關(guān)鍵詞可以暫停async
函數(shù)的執(zhí)行,等待Promise
解決。
async function fetchData() { let data = await fetch('url'); data = await data.json(); return data; }
2. 錯(cuò)誤處理
使用try...catch
結(jié)構(gòu)處理async/await
中的錯(cuò)誤。
async function fetchData() { try { let response = await fetch('url'); response = await response.json(); return response; } catch (error) { console.error('Fetching data error:', error); } }
3. 并行執(zhí)行
Promise.all()
可以用來(lái)并行執(zhí)行多個(gè)await
操作。
async function fetchMultipleUrls(urls) { const promises = urls.map(url => fetch(url).then(r => r.json())); return await Promise.all(promises); }
4. 條件異步
根據(jù)條件執(zhí)行await
。
async function fetchData(condition) { if (condition) { return await fetch('url'); } return 'No fetch needed'; }
5. 循環(huán)中的await
在循環(huán)中使用await
時(shí),每次迭代都會(huì)等待。
async function sequentialStart(urls) { for (const url of urls) { const response = await fetch(url); console.log(await response.json()); } }
6. 異步迭代器
對(duì)于異步迭代器(例如Node.js中的Streams),可以使用for-await-of
循環(huán)。
async function processStream(stream) { for await (const chunk of stream) { console.log(chunk); } }
7. await之后立即解構(gòu)
直接在await
表達(dá)式后使用解構(gòu)。
async function getUser() { const { data: user } = await fetch('user-url').then(r => r.json()); return user; }
8. 使用默認(rèn)參數(shù)避免無(wú)效的await
如果await
可能是不必要的,可以使用默認(rèn)參數(shù)避免等待。
async function fetchData(url = 'default-url') { const response = await fetch(url); return response.json(); }
9. await在類的方法中
在類的方法中使用async/await
。
class DataFetcher { async getData() { const data = await fetch('url').then(r => r.json()); return data; } }
10. 立刻執(zhí)行的async箭頭函數(shù)
可以立即執(zhí)行的async
箭頭函數(shù)。
(async () => { const data = await fetch('url').then(r => r.json()); console.log(data); })();
11. 使用async/await進(jìn)行延時(shí)
利用async/await
實(shí)現(xiàn)延時(shí)。
function delay(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } async function delayedLog(item) { await delay(1000); console.log(item); }
12. 使用async/await處理事件監(jiān)聽器
在事件處理函數(shù)中使用async/await
。
document.getElementById('button').addEventListener('click', async (event) => { event.preventDefault(); const data = await fetch('url').then(r => r.json()); console.log(data); });
13. 以順序方式處理數(shù)組
使用async/await
以確定的順序處理數(shù)組。
async function processArray(array) { for (const item of array) { await delayedLog(item); } console.log('Done!'); }
14. 組合async/await與destructuring以及spread運(yùn)算符
結(jié)合使用async/await
,解構(gòu)和展開操作符。
async function getConfig() { const { data, ...rest } = await fetch('config-url').then(r => r.json()); return { config: data, ...rest }; }
15. 在對(duì)象方法中使用async/await
將async
方法作為對(duì)象的屬性。
const dataRetriever = { async fetchData() { return await fetch('url').then(r => r.json()); } };
16. 異步生成器函數(shù)
使用async
生成器函數(shù)結(jié)合yield
。
async function* asyncGenerator(array) { for (const item of array) { yield await processItem(item); } }
17. 使用頂級(jí)await
在模塊頂層使用await
(需要特定的JavaScript環(huán)境支持)。
// ECMAScript 2020引入頂級(jí)await特性, 部署時(shí)注意兼容性 const config = await fetch('config-url').then(r => r.json());
18. async/await與IIFE結(jié)合
將async
函數(shù)與立即執(zhí)行函數(shù)表達(dá)式(IIFE)結(jié)合。
(async function() { const data = await fetch('url').then(r => r.json()); console.log(data); })();
19. 使用async/await優(yōu)化遞歸調(diào)用
優(yōu)化遞歸函數(shù)。
async function asyncRecursiveFunction(items) { if (items.length === 0) return 'done'; const currentItem = items.shift(); await delay(1000); console.log(currentItem); return asyncRecursiveFunction(items); }
20. 在switch語(yǔ)句中使用await
在switch
語(yǔ)句的每個(gè)case
中使用await
。
async function fetchDataBasedOnType(type) { switch (type) { case 'user': return await fetch('user-url').then(r => r.json()); case 'post': return await fetch('post-url').then(r => r.json()); default: throw new Error('Unknown type'); } }
以上就是20個(gè)你不得不知道的JS async/await實(shí)用技巧的詳細(xì)內(nèi)容,更多關(guān)于JS async/await技巧的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
論壇轉(zhuǎn)貼工具中用到的正則表達(dá)式學(xué)習(xí)正則的好例子
論壇轉(zhuǎn)貼工具中用到的正則表達(dá)式學(xué)習(xí)正則的好例子...2007-11-11JS實(shí)現(xiàn)頁(yè)面內(nèi)跳轉(zhuǎn)的簡(jiǎn)單代碼
這篇文章主要介紹了JS實(shí)現(xiàn)頁(yè)面內(nèi)跳轉(zhuǎn)的簡(jiǎn)單代碼,需要的朋友可以參考下2017-09-09在IE上直接編輯網(wǎng)頁(yè)內(nèi)容的js代碼(IE地址欄js)
在IE上直接編輯網(wǎng)頁(yè)內(nèi)容2009-04-04下載站常用的點(diǎn)擊下載地址提示設(shè)hao123為首頁(yè)的js代碼
最近很多下載站下載文件的時(shí)候都提示設(shè)置hao123為首頁(yè),這里我們來(lái)分享下具體的實(shí)現(xiàn)方法,需要的朋友可以參考下2013-10-10JS 實(shí)現(xiàn)導(dǎo)航欄懸停效果(續(xù))
上次導(dǎo)航欄懸停的那個(gè)頁(yè)面在IE上運(yùn)行的時(shí)候,會(huì)出導(dǎo)航欄不停的抖動(dòng)問(wèn)題,在本文已有完美的解決方法,將導(dǎo)航欄的定位方式由原來(lái)的absolute改為fixed即可2013-09-09Javascript?promise.all的用法介紹(簡(jiǎn)潔易懂)
這篇文章主要給大家介紹了關(guān)于Javascript?promise.all用法的相關(guān)資料,Promise.all()方法是一個(gè)Promise對(duì)象方法,可以將多個(gè)Promise實(shí)例包裝成一個(gè)新的Promise對(duì)象,最終返回一個(gè)數(shù)組,需要的朋友可以參考下2023-07-07js控制文本框只能輸入中文、英文、數(shù)字與指定特殊符號(hào)的實(shí)現(xiàn)代碼
下面小編就為大家?guī)?lái)一篇js控制文本框只能輸入中文、英文、數(shù)字與指定特殊符號(hào)的實(shí)現(xiàn)代碼。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2016-09-09