NodeJS Program to Async Generator Basics with Explanation
NodeJS
Hard
Async & Event Loop
29 views
1 min read
80 words
This problem helps you practice core NodeJS fundamentals in a practical way. It builds intuition around async, generator, basic. Let’s break it down step by step so you can implement it confidently.
Problem Statement
Create an async generator that yields values with delay.
Input Format
No input.
Output Format
Print lines.
Constraints
Use for await...of.
Code Solution
This explanation is written for learning purposes and to help beginners understand the concept clearly.
function delay(ms) {
return new Promise((r) => setTimeout(r, ms));
}
async function* gen() {
for (let i = 1; i <= 3; i++) {
await delay(10);
yield i;
}
}
(async () => {
for await (const v of gen()) console.log(v);
})();
Output Example
No sample I/O is provided for this question.
Common Mistakes
- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).
Solution Guide
Problem
Create an async generator that yields values with delay.
Input / Output
Constraints
Use for await...of.
Details
Common Mistakes
- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).
Official Solution
function delay(ms) {
return new Promise((r) => setTimeout(r, ms));
}
async function* gen() {
for (let i = 1; i <= 3; i++) {
await delay(10);
yield i;
}
}
(async () => {
for await (const v of gen()) console.log(v);
})();
Solutions (0)
No solutions submitted yet. Be the first!