Junior — Middle
How have you used OpenShift in your projects and what main tasks have you solved with its help?
sobes.tech AI
Answer from AI
In Node.js, asynchrony is a key feature that allows the program to avoid blocking execution during I/O operations.
Main asynchronous operations and functions:
- Callbacks: functions passed as arguments and called after the operation completes.
const fs = require('fs');
fs.readFile('file.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
- Promises: objects representing the result of an async operation, with
.then()and.catch()methods.
fs.promises.readFile('file.txt', 'utf8')
.then(data => console.log(data))
.catch(err => console.error(err));
- async/await: syntactic sugar over promises, allowing writing async code in a synchronous style.
async function readFile() {
try {
const data = await fs.promises.readFile('file.txt', 'utf8');
console.log(data);
} catch (err) {
console.error(err);
}
}
readFile();
- EventEmitter: allows reacting to events, which is also a form of asynchronous programming.
Thus, in Node.js, asynchronous operations enable efficient working with files, network, and other resources without blocking the main execution thread.