Skip to content

Instantly share code, notes, and snippets.

@jherax
Created July 4, 2024 23:59
Show Gist options
  • Save jherax/eecc224d5d03ed7aa1b10497e13878cc to your computer and use it in GitHub Desktop.
Save jherax/eecc224d5d03ed7aa1b10497e13878cc to your computer and use it in GitHub Desktop.
Tricks with JS Async / Await
/**
* 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 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