Skip to content

Instantly share code, notes, and snippets.

@Kcko
Last active February 8, 2025 12:21
Show Gist options
  • Save Kcko/ca64aa4bdc723af87c6b03e20f6545d7 to your computer and use it in GitHub Desktop.
Save Kcko/ca64aa4bdc723af87c6b03e20f6545d7 to your computer and use it in GitHub Desktop.
/*
@url https://levelup.gitconnected.com/7-simple-async-await-tricks-for-developers-who-hate-asynchronous-javascript-fe370ac7fe72
*/
// 1. Use Promise.allSettled() for Safer Batch Processing
const results = await Promise.allSettled([
fetchData1(),
fetchData2(),
fetchData3(),
]);
results.forEach(result => {
if (result.status === 'fulfilled') {
console.log('Success:', result.value);
} else {
console.error('Failed:', result.reason);
}
});
// 2. Use Timeouts to Prevent Hanging Promises
const withTimeout = (promise, ms) =>
Promise.race([
promise,
new Promise((_, reject) => setTimeout(() => reject(new Error('Timeout')), ms)),
]);
try {
const data = await withTimeout(fetchData(), 5000);
} catch (err) {
console.error(err.message); // "Timeout" if it takes too long
}
// 3. Sequential Loops with Async/Await
const urls = ['url1', 'url2', 'url3'];
for (const url of urls) {
const data = await fetch(url);
console.log(data);
}
// 4. Dynamic Delays with await
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
console.log('Start');
await delay(2000); // Waits 2 seconds
console.log('End');
// 5. Always Use try...catch Inside Async Functions
async function fetchData(url) {
try {
const response = await fetch(url);
if (!response.ok) throw new Error('Fetch failed');
return await response.json();
} catch (err) {
console.error('Error:', err.message);
return null;
}
}
// 6. await Outside Loops to Batch Workloads
const urls = ['url1', 'url2', 'url3'];
const responses = await Promise.all(urls.map(url => fetch(url)));
const data = await Promise.all(responses.map(res => res.json()));
console.log(data);
// 7 ... fking yield => dont care
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment