Last active
June 11, 2019 04:53
-
-
Save justsml/039b6d60ec3feed7f4acaa4caf2f008c to your computer and use it in GitHub Desktop.
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
/* | |
The number of stack frames that can | |
(reasonably) be tracked is small (~dozens). | |
When you run code like below, the inner async `writeFile` | |
can 'lose' its prior frame(s) 2 main ways: | |
1. When the outer `forEach` completes (w/ asyncs still running) | |
the stack pops off the completed synchronous frames into | |
the ether. Any later failure may only have a bit of async | |
framework functions to reference. | |
2. A lot of (sync) code after `forEach` can push frames out of the debuggers view.* | |
*/ | |
const files = ['file1', 'file2', 'file3'] | |
files.forEach(file => { | |
// This `writeFile()` might as well be shot into space | |
fs.writeFile(file, `name: ${file}`, (err, data) => { | |
// FACT: if a callback falls in space, no user will hear it* | |
}) | |
}) | |
// [disclaimer: The stack cannot jettison things into space...] | |
// [Also: Liberties were taken describing stack. #sorrynotsorry CS friends 😇] |
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
// Solution (Promises Version) | |
const files = ['file1', 'file2', 'file3'] | |
const runningTasks = files.map(file => { | |
// **return on your async call*** (and if needed, chain additional calls) | |
return fs.writeFileAsync(file, `name: ${file}`, 'utf8') | |
}) | |
// Now we can feed the tasks into a `Promise.all()` | |
(async () => { | |
try { | |
const completedTasks = await Promise.all(runningTasks) | |
console.log(completedTasks) | |
} catch (error) { | |
// we can find what's going on here: | |
console.error('WILL HAVE USEFUL STACK TRACE:', error) | |
} | |
}) | |
// Note: This pattern takes a _tiny_ bit more RAM | |
// make sure to test in super constrained environments. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment