Created
July 4, 2024 23:59
-
-
Save jherax/eecc224d5d03ed7aa1b10497e13878cc to your computer and use it in GitHub Desktop.
Tricks with JS Async / Await
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Dynamic imports allow you to import modules asynchronously. | |
* This can significantly improve the load time of web applications | |
* by splitting the code into smaller chunks and loading them on demand. | |
*/ | |
async function loadModule(moduleName) { | |
try { | |
const module = await import(`./modules/${moduleName}.js`); | |
module.default(); // Assuming the module exports a default function | |
// module.namedExport(); | |
} catch (error) { | |
console.error('Failed to load module:', error); | |
} | |
} | |
loadModule('myDynamicModule'); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* This pattern can be useful for processing large datasets that are | |
* fetched from an API in chunks or dealing with real-time data streams. | |
*/ | |
async function* asyncDataGenerator() { | |
let moreData = true; | |
let page = 1; | |
while (moreData) { | |
const data = await fetch(`https://api.example.com/data?page=${page}`); | |
const jsonData = await data.json(); | |
yield* jsonData.items; // Assuming the data comes in a property called items | |
moreData = jsonData.moreData; // Assuming API indicates if there's more data | |
page += 1; | |
} | |
} | |
async function processData() { | |
for await (let item of asyncDataGenerator()) { | |
console.log(item); // Process each item | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment