Understanding Node.js Event-Driven Architecture
medium.freecodecamp.com
medium.freecodecamp.com
I wish that promises had a concept similar to this. It's simply too annoying for me to manually refactor a bunch of Promise.all() calls to manually adjust the concurrency of the logic flow compared to using the dependency pattern of async.auto().
And based on what I've seen this is a common problem in both async functions, generators, and promises. Since it is difficult to properly execute a tree of functional steps with the maximal concurrency I see code all the time which just runs async functions or promises in a series instead of taking advantage of the ability to concurrently execute two branches of the tree at the same time.
Promises are easier to compose because you can pass them around as values. Meanwhile callbacks are used only for their side-effects, they do not return anything.
Have not yet moved to async/await though.
The event loop is not something you can be abstracted from, it is a core component of node that you need to be aware of all the time.
If you have long lived code within an event loop tick you will starve the I/O and everything will start timing out.
Then, freecodecamp (and every other coding camp) do an incredible disservice to society by telling everyone that ever touched a computer for 5 minutes that they're "full-stack engineers", a denomination that is in itself very questionable too.
It's like calling myself a veterinarian because I walked my dog, or calling myself a chef because I fried an egg. These camps promote a very oversimplified vision of what it means to be a software engineer.
I think the balance is missing here.
Does anyone know if the situation has changed by now and you can obtain promises from core functions directly?
That being said, there are some fantastic libraries which you can use as a drop-in replacement for the core libraries provide a promise based API, but nothing in core directly.
So when you require libraries, you can do so like:
const fs = Promise.promisifyAll(require('fs'))
// ... later
const fileContents = await fs.readFileAsync('filename.txt')
Basically it just adds "Async" after all functions that use node style callbacks. const fs = require("fs");
fs.exists(`${ __dirname }/1`, (exists1) => {
fs.exists(`${ __dirname }/2`, (exists2) => {
console.log(JSON.stringify([exists1, exists2]));
});
});
vs const fs = require("mz/fs");
Promise.all([
fs.exists(`${ __dirname }/1`),
fs.exists(`${ __dirname }/2`),
])
.then((existers) => {
console.log(JSON.stringify(existers));
});
Or const fs = require("mz/fs");
(async () => {
console.log(JSON.stringify(await Promise.all([
fs.exists(`${ __dirname }/1`),
fs.exists(`${ __dirname }/2`),
])));
})();