20 Js async/await usages that you have to know
1. Basic usage
async
The function returns aPromise
,andawait
Keywords can be pausedasync
Function execution, waitingPromise
solve.
async function fetchData() { let data = await fetch('url'); data = await (); return data; }
2. Error handling
usetry...catch
Structural processingasync/await
Error in.
async function fetchData() { try { let response = await fetch('url'); response = await (); return response; } catch (error) { ('Fetching data error:', error); } }
3. Parallel execution
()
Can be used to execute multipleawait
operate.
async function fetchMultipleUrls(urls) { const promises = (url => fetch(url).then(r => ())); return await (promises); }
4. Conditional asynchronous
Perform according to the conditionsawait
。
async function fetchData(condition) { if (condition) { return await fetch('url'); } return 'No fetch needed'; }
5. Await in a loop
Use in a loopawait
When, each iteration will wait.
async function sequentialStart(urls) { for (const url of urls) { const response = await fetch(url); (await ()); } }
6. Asynchronous iterator
For asynchronous iterators (for example Streams), you can usefor-await-of
cycle.
async function processStream(stream) { for await (const chunk of stream) { (chunk); } }
7. Deconstruct immediately after await
Directly inawait
Deconstruction is used after expression.
async function getUser() { const { data: user } = await fetch('user-url').then(r => ()); return user; }
8. Use default parameters to avoid invalid await
ifawait
It may be unnecessary, and you can use the default parameters to avoid waiting.
async function fetchData(url = 'default-url') { const response = await fetch(url); return (); }
9. await in class method
Use in class methodsasync/await
。
class DataFetcher { async getData() { const data = await fetch('url').then(r => ()); return data; } }
10. The async arrow function that is executed immediately
Can be executed immediatelyasync
Arrow function.
(async () => { const data = await fetch('url').then(r => ()); (data); })();
11. Use async/await for delay
useasync/await
Implement delay.
function delay(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } async function delayedLog(item) { await delay(1000); (item); }
12. Use async/await to handle event listeners
Use in event handler functionsasync/await
。
('button').addEventListener('click', async (event) => { (); const data = await fetch('url').then(r => ()); (data); });
13. Processing arrays in sequential manner
useasync/await
Process the array in a definite order.
async function processArray(array) { for (const item of array) { await delayedLog(item); } ('Done!'); }
14. Combining async/await with destructuring and spread operators
Use in combinationasync/await
, deconstruct and expand operators.
async function getConfig() { const { data, ...rest } = await fetch('config-url').then(r => ()); return { config: data, ...rest }; }
15. Use async/await in object methods
Willasync
Methods are attributes of objects.
const dataRetriever = { async fetchData() { return await fetch('url').then(r => ()); } };
16. Asynchronous generator function
useasync
Generator function combinationyield
。
async function* asyncGenerator(array) { for (const item of array) { yield await processItem(item); } }
17. Use top await
Used on top of the moduleawait
(Requires specific JavaScript environment support).
// ECMAScript 2020 introduces top await features, pay attention to compatibility when deployingconst config = await fetch('config-url').then(r => ());
18. Async/await combined with IIFE
Willasync
Functions are combined with Immediate Execution Function Expression (IIFE).
(async function() { const data = await fetch('url').then(r => ()); (data); })();
19. Optimize recursive calls using async/await
Optimize recursive functions.
async function asyncRecursiveFunction(items) { if ( === 0) return 'done'; const currentItem = (); await delay(1000); (currentItem); return asyncRecursiveFunction(items); }
20. Use await in switch statement
existswitch
Each statementcase
Used inawait
。
async function fetchDataBasedOnType(type) { switch (type) { case 'user': return await fetch('user-url').then(r => ()); case 'post': return await fetch('post-url').then(r => ()); default: throw new Error('Unknown type'); } }
The above are the detailed contents of 20 practical JS async/await techniques that you have to know. For more information about JS async/await techniques, please follow my other related articles!