Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/*
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
You can’t perform that action at this time.