✅ 1. Core Node.js Concepts - Asynchronous Programming Flashcards
What is asynchronous programming in Node.js?
It allows tasks to run non-blocking and continue execution without waiting for previous operations to complete.
What is a callback in Node.js?
A function passed as an argument to another function, executed after the completion of an asynchronous operation.
What is callback hell?
It refers to nested callbacks that make the code hard to read and maintain.
Convert this callback function to a promise:
fs.readFile(‘file.txt’, (err, data) => {
if (err) throw err;
console.log(data);
});
const readFileAsync = (file) => {
return new Promise((resolve, reject) => {
fs.readFile(file, (err, data) => {
if (err) reject(err);
else resolve(data);
});
});
};
What is a Promise?
An object that represents the eventual completion or failure of an asynchronous operation.
What are the three states of a Promise?
Pending: Initial state.
Fulfilled: Operation completed successfully.
Rejected: Operation failed.
What is the difference between Promise.all() and Promise.race()?
Promise.all(): Resolves when all promises resolve.
Promise.race(): Resolves as soon as one promise resolves or rejects.
What is the output of this code?
Promise.resolve(‘A’)
.then((res) => console.log(res))
.finally(() => console.log(‘Finally’));
A
Finally
What does async do in Node.js?
It marks a function to always return a promise, allowing the use of await inside it.
What does await do in Node.js?
It pauses the execution of the function until the promise resolves.
What is the output of this code?
async function example() {
console.log(‘A’);
await Promise.resolve();
console.log(‘B’);
}
example();
console.log(‘C’);
A
C
B
How do you handle errors in async/await?
Using try-catch blocks:
try {
const data = await fetchData();
} catch (error) {
console.error(error);
}
What is the difference between .then() and await?
.then(): Used with chained promises.
await: Makes the code look synchronous and easier to read.
What does Promise.reject() do?
It immediately returns a rejected promise with the specified reason.
What is the output of this code?
const p = new Promise((resolve, reject) => {
reject(‘Error’);
});
p.catch(err => console.log(err))
.finally(() => console.log(‘Done’));
Error
Done
What is Promise.allSettled()?
It waits for all promises to settle (resolve or reject) and returns their results.
What is the output of this code?
const p1 = Promise.resolve(‘A’);
const p2 = Promise.reject(‘Error’);
Promise.allSettled([p1, p2]).then(console.log);
[ { status: ‘fulfilled’, value: ‘A’ },
{ status: ‘rejected’, reason: ‘Error’ } ]
What is the purpose of util.promisify() in Node.js?
It converts callback-based functions into promise-based functions.
Convert this callback to a promise using util.promisify():
const fs = require(‘fs’);
fs.readFile(‘file.txt’, (err, data) => {
if (err) throw err;
console.log(data.toString());
});
const { promisify } = require(‘util’);
const readFileAsync = promisify(fs.readFile);
readFileAsync(‘file.txt’).then(console.log).catch(console.error);
What happens if you omit await in an async function?
The function returns a promise but does not wait for the operation to complete.
What is the output of this code?
async function test() {
return ‘Hello’;
}
console.log(test());
Promise { ‘Hello’ }
What is the output of this code?
async function test() {
throw new Error(‘Oops!’);
}
test().catch(console.error);
Error: Oops!
What is Promise.any() in Node.js?
It resolves when at least one of the promises resolves, otherwise rejects with an aggregate error.
What is the output of this code?
Promise.any([
Promise.reject(‘Error1’),
Promise.resolve(‘Success’),
Promise.reject(‘Error2’)
]).then(console.log);
Success
What is the purpose of Promise.all()?
It waits for all promises to resolve or rejects if one fails.
How do you create a delay with Promise?
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
What is the output of this code?
setTimeout(() => console.log(‘Timeout’), 0);
Promise.resolve().then(() => console.log(‘Promise’));
Promise
Timeout
Microtasks (Promises) run before timers.
What is the difference between process.nextTick() and setImmediate() in async operations?
process.nextTick() runs before the next event loop iteration.
setImmediate() runs in the check phase.
How can you cancel a promise?
By using AbortController:
const controller = new AbortController();
const { signal } = controller;
setTimeout(() => controller.abort(), 1000);
What is the best practice for handling multiple async operations?
Use Promise.all() or Promise.allSettled() to handle multiple async calls efficiently.