Skip to content

Instantly share code, notes, and snippets.

@justsml
Last active June 11, 2019 04:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save justsml/039b6d60ec3feed7f4acaa4caf2f008c to your computer and use it in GitHub Desktop.
Save justsml/039b6d60ec3feed7f4acaa4caf2f008c to your computer and use it in GitHub Desktop.
/*
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 😇]
// 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