Lecture Notes Of Class 17: Understanding
Asynchronous Programming in Node.js
Objective:
To understand and master
asynchronous programming techniques in Node.js, enabling the execution of
non-blocking code that improves performance in applications.
1. Introduction to
Asynchronous Programming
In Node.js, asynchronous
programming allows you to handle multiple tasks simultaneously without blocking
the main thread. This is crucial for high-performance applications, as it helps
in handling many I/O operations, such as file reading, database queries, or
network requests, without freezing the application.
Synchronous programming
blocks the execution of code until a task is completed. In contrast, asynchronous
programming enables other tasks to continue while waiting for
time-consuming operations to finish.
2. Callback Functions
Node.js uses callback
functions to manage asynchronous tasks. A callback is a function passed as an
argument to another function, which is executed once the operation completes.
Example of a Callback:
js
CopyEdit
console.log("Start");
setTimeout(() => {
console.log("This is asynchronous");
}, 2000);
console.log("End");
Explanation:
- setTimeout()
is an asynchronous operation that waits for a specified time (2 seconds in
this case) before executing the provided callback function.
- The
output will be:
sql
CopyEdit
Start
End
This is asynchronous
3. Lab Task 1: Using setTimeout()
and setInterval()
3.1 setTimeout():
setTimeout() is used to
execute a piece of code after a certain delay.
Syntax:
js
CopyEdit
setTimeout(function,
delayInMilliseconds);
Example:
js
CopyEdit
setTimeout(() => {
console.log("Hello after 3 seconds");
}, 3000);
Here, the code inside the
setTimeout() function will run after 3 seconds.
3.2 setInterval():
setInterval() repeatedly
executes a function after a specified interval.
Syntax:
js
CopyEdit
setInterval(function,
delayInMilliseconds);
Example:
js
CopyEdit
let counter = 0;
let intervalId = setInterval(()
=> {
counter++;
console.log(`Counter: ${counter}`);
if (counter === 5) {
clearInterval(intervalId); // Stop the
interval after 5 iterations
}
}, 1000);
Here, the code inside setInterval()
will execute every 1 second, printing the counter value, and it will stop after
5 iterations with clearInterval().
4. Lab Task 2: Exploring
Asynchronous Operations Using async/await
async and await are
modern JavaScript features that simplify working with asynchronous code. They
are built on top of Promises and allow us to write asynchronous code in a
synchronous style, improving readability.
4.1 async Functions:
An async function always
returns a Promise. If the function contains a return statement, the resolved
value will be wrapped in a Promise.
Syntax:
js
CopyEdit
async function example()
{
return "Hello";
}
example().then(console.log); // Outputs: Hello
4.2 await Keyword:
The await keyword is used
inside an async function. It waits for a Promise to resolve or reject and
returns the resolved value.
Syntax:
js
CopyEdit
let result = await someAsyncOperation();
Example:
js
CopyEdit
async function fetchData()
{
let data = await new Promise(resolve => setTimeout(()
=> resolve("Fetched Data"), 2000));
console.log(data);
}
console.log("Start");
fetchData();
console.log("End");
Explanation:
- fetchData()
is an asynchronous function that uses await to pause its execution until
the Promise resolves (after 2 seconds).
- The
output will be:
sql
CopyEdit
Start
End
Fetched Data
5. Lab Task 3: Using Promise
to Handle Asynchronous Results
Promises are a more
powerful way to manage asynchronous operations. A Promise represents a value
that may be available now, or in the future, or never.
5.1 Creating a Promise:
You can create a Promise
using the new Promise() constructor, which takes a function with two arguments:
resolve (if the operation succeeds) and reject (if the operation fails).
Syntax:
js
CopyEdit
let promise = new Promise((resolve,
reject) => {
// Perform some asynchronous operation
if (/* success condition */) {
resolve("Success");
} else {
reject("Failure");
}
});
Example:
js
CopyEdit
let myPromise = new Promise((resolve,
reject) => {
let success = true;
setTimeout(() => {
if (success) {
resolve("Operation Successful");
} else {
reject("Operation Failed");
}
}, 2000);
});
myPromise
.then(result => console.log(result)) // Outputs: Operation Successful
.catch(error => console.log(error));
5.2 Handling Multiple
Promises with Promise.all():
Promise.all() allows you
to run multiple Promises concurrently and wait until all of them are resolved.
Example:
js
CopyEdit
let promise1 = new Promise(resolve
=> setTimeout(() => resolve("First Promise"), 1000));
let promise2 = new Promise(resolve
=> setTimeout(() => resolve("Second Promise"), 2000));
Promise.all([promise1,
promise2])
.then(results => {
console.log(results); // Outputs: [ 'First Promise', 'Second
Promise' ]
});
5.3 Chaining Promises:
You can chain .then() to
perform operations after the Promise resolves.
Example:
js
CopyEdit
let myAsyncTask = new Promise((resolve,
reject) => {
setTimeout(() => resolve("Task
Completed"), 2000);
});
myAsyncTask
.then(result => {
console.log(result); // Outputs: Task Completed
return "Next Task";
})
.then(nextResult => console.log(nextResult)); // Outputs: Next Task
6. Error Handling in
Asynchronous Code
Asynchronous operations,
such as those using setTimeout, Promise, or async/await, can fail, and it’s
essential to handle errors properly to avoid unexpected crashes.
6.1 Using try/catch with async/await:
When using async/await,
you can use try/catch blocks to catch errors.
Example:
js
CopyEdit
async function asyncTask()
{
try {
let result = await new Promise((resolve,
reject) => {
let success = false;
if (success) {
resolve("Task successful");
} else {
reject("Task failed");
}
});
console.log(result);
} catch (error) {
console.error("Error:", error);
}
}
asyncTask();
Here, the code inside the
catch block will execute if there is an error in the asynchronous operation.
7. Conclusion
Asynchronous programming
in Node.js is crucial for building efficient and scalable applications. By
mastering techniques like setTimeout(), setInterval(), Promise, and async/await,
you will be able to handle multiple tasks concurrently, leading to improved
performance. Always ensure proper error handling in asynchronous operations to
avoid unexpected issues.
8. Lab Tasks Recap
1.
Using setTimeout() and setInterval():
Timing events and repeating tasks asynchronously.
2.
Exploring Asynchronous Operations
with async/await: Writing cleaner asynchronous code.
3.
Handling Asynchronous Results with Promise:
Managing asynchronous operations with Promises and chaining.
By completing these
tasks, you will gain hands-on experience with key asynchronous techniques in
Node.js.
4o mini
You said:
Solutions of : Using
setTimeout() and setInterval(): Timing events and repeating tasks
asynchronously. Exploring Asynchronous Operations with async/await: Writing
cleaner asynchronous code. Handling Asynchronous Results with Promise: Managing
asynchronous operations with Promises and chaining.
ChatGPT said:
ChatGPT
Here are the solutions
for the tasks mentioned in your class:
1. Using setTimeout() and
setInterval(): Timing Events and Repeating Tasks Asynchronously
Task 1: Using setTimeout()
setTimeout() is used to
execute a function after a specified delay.
Solution:
js
CopyEdit
// Using setTimeout to
print a message after 3 seconds
console.log("Start");
setTimeout(() => {
console.log("Hello after 3 seconds");
}, 3000); // 3000 milliseconds = 3 seconds
console.log("End");
Explanation:
- The
message "Start" will print immediately.
- The
setTimeout() function will delay the execution of the message "Hello
after 3 seconds" by 3 seconds.
- The
message "End" will print immediately after "Start"
without waiting for the setTimeout() to complete.
Output:
sql
CopyEdit
Start
End
Hello after 3 seconds
Task 2: Using setInterval()
setInterval() repeatedly
executes a function at a specified interval.
Solution:
js
CopyEdit
// Using setInterval to
print counter every 1 second
let counter = 0;
let intervalId = setInterval(()
=> {
counter++;
console.log(`Counter: ${counter}`);
if (counter === 5) {
clearInterval(intervalId); // Stop the
interval after 5 iterations
console.log("Interval stopped.");
}
}, 1000); // 1000 milliseconds = 1 second
Explanation:
- The
setInterval() function prints the value of counter every 1 second.
- The
interval is cleared once counter reaches 5 by calling clearInterval(intervalId).
Output:
makefile
CopyEdit
Counter: 1
Counter: 2
Counter: 3
Counter: 4
Counter: 5
Interval stopped.
2. Exploring Asynchronous
Operations with async/await: Writing Cleaner Asynchronous Code
The async and await
keywords simplify handling asynchronous operations and improve readability.
Solution:
js
CopyEdit
// Using async/await to
handle asynchronous code in a cleaner way
async function fetchData()
{
console.log("Start fetching
data...");
// Simulating an asynchronous operation using
a Promise with setTimeout
let data = await new Promise(resolve => setTimeout(()
=> resolve("Fetched Data"), 2000));
console.log(data); // Prints "Fetched Data" after 2
seconds
console.log("End of fetch
operation");
}
console.log("Start");
fetchData(); // Calling the async function
console.log("End");
Explanation:
- The
fetchData() function is async, meaning it returns a Promise.
- The
await keyword pauses the execution of fetchData() until the Promise is
resolved (after 2 seconds).
- The
execution continues after the Promise resolves, and "Fetched
Data" is printed.
Output:
sql
CopyEdit
Start
End
Start fetching data...
End of fetch operation
Fetched Data
3. Handling Asynchronous
Results with Promise: Managing Asynchronous Operations with Promises and
Chaining
Promises are used to
handle asynchronous results, and they provide methods like .then() and .catch()
for chaining operations.
Solution 1: Basic Promise
with then() and catch()
js
CopyEdit
// Creating a Promise to
simulate an asynchronous task
let myPromise = new Promise((resolve,
reject) => {
let success = true; // You can toggle this to false to test
failure
setTimeout(() => {
if (success) {
resolve("Operation Successful");
} else {
reject("Operation Failed");
}
}, 2000);
});
// Handling the resolved
or rejected value with .then() and .catch()
myPromise
.then(result => console.log(result)) // Handles the resolved value
.catch(error => console.log(error)); // Handles the rejected value
Explanation:
- The
myPromise is created and will resolve with "Operation
Successful" if success is true or reject with "Operation
Failed" if success is false.
- The
.then() method handles the resolved value, while .catch() handles any
errors or rejections.
Output (if success is
true):
CopyEdit
Operation Successful
Solution 2: Chaining
Multiple Promises
You can chain multiple .then()
calls to handle sequential asynchronous operations.
js
CopyEdit
// Chaining multiple
Promises
let task1 = new Promise(resolve
=> setTimeout(() => resolve("Task 1 completed"), 2000));
let task2 = new Promise(resolve
=> setTimeout(() => resolve("Task 2 completed"), 3000));
task1
.then(result => {
console.log(result); // Task 1 completed
return task2; // Return the next Promise to continue
chaining
})
.then(result => {
console.log(result); // Task 2 completed
})
.catch(error => console.log(error)); // Catch any error during the Promise chain
Explanation:
- The
task1 Promise resolves after 2 seconds, and its result is logged.
- The
result of task1 is passed to the next .then() where task2 is called, which
resolves after 3 seconds.
- If
any error occurs during the chain, it will be caught in the .catch()
method.
Output:
arduino
CopyEdit
Task 1 completed
Task 2 completed
Solution 3: Using Promise.all()
for Multiple Promises
Promise.all() is useful
when you want to wait for multiple asynchronous operations to complete before
continuing.
js
CopyEdit
let promise1 = new Promise(resolve
=> setTimeout(() => resolve("First Promise completed"), 2000));
let promise2 = new Promise(resolve
=> setTimeout(() => resolve("Second Promise completed"), 3000));
Promise.all([promise1,
promise2])
.then(results => {
console.log(results); // Outputs an array: [ 'First Promise
completed', 'Second Promise completed' ]
})
.catch(error => console.log(error));
Explanation:
- Promise.all()
takes an array of promises and resolves when all promises in the array are
resolved.
- The
results are returned as an array in the same order they were passed.
Output:
css
CopyEdit
[ 'First Promise
completed', 'Second Promise completed' ]
Summary of Solutions:
1.
setTimeout() is
used to execute code after a delay, while setInterval() is used for
repeated execution at intervals.
2.
async/await
simplifies asynchronous code by allowing you to write code that looks
synchronous, even if it performs asynchronous operations.
3.
Promise
provides a cleaner way to handle asynchronous operations, with .then(), .catch(),
and chaining. Promise.all() can be used when waiting for multiple
asynchronous tasks to complete simultaneously.
By mastering these
asynchronous techniques, you can effectively handle tasks like file reading,
network requests, and other time-consuming operations without blocking the
application, making it more efficient and responsive.
4o mini
You said:
Write 10 assignments with
solution and explanation in detail on above concept
ChatGPT said:
ChatGPT
Here are 10
assignments based on the concepts of Asynchronous Programming in Node.js
using setTimeout(), setInterval(), async/await, and Promise. Each assignment
comes with a detailed solution and explanation.
Assignment 1: Using setTimeout()
for Delayed Execution
Task:
Create a program that prints "Hello, World!" after 5 seconds.
Solution:
js
CopyEdit
setTimeout(() => {
console.log("Hello, World!");
}, 5000); // 5000 milliseconds = 5 seconds
Explanation:
- The
setTimeout() function delays the execution of the provided callback by
5000 milliseconds (5 seconds).
- Once
the delay is over, it prints "Hello, World!" to the console.
Assignment 2: Using setInterval()
to Repeat a Task
Task:
Write a program that logs the current time every 2 seconds, and stops after 6
logs.
Solution:
js
CopyEdit
let counter = 0;
let intervalId = setInterval(()
=> {
console.log(new Date().toLocaleTimeString()); // Print current time
counter++;
if (counter === 6) {
clearInterval(intervalId); // Stop the interval after 6 logs
}
}, 2000); // 2000 milliseconds = 2 seconds
Explanation:
- setInterval()
repeats the function every 2 seconds, logging the current time.
- After
6 iterations, the clearInterval() function is called to stop the interval.
Assignment 3: Using async/await
for Delayed Execution
Task:
Write an async function that waits for 4 seconds before printing "Task
Completed".
Solution:
js
CopyEdit
async function waitAndPrint()
{
console.log("Start waiting...");
await new Promise(resolve => setTimeout(resolve,
4000)); // Wait for 4 seconds
console.log("Task Completed");
}
waitAndPrint();
Explanation:
- The
waitAndPrint() function is asynchronous.
- It
uses await to pause execution until the Promise inside setTimeout()
resolves after 4 seconds.
- After
waiting, "Task Completed" is printed.
Assignment 4: Handling
Multiple Asynchronous Tasks with Promise.all()
Task:
Create two asynchronous tasks using setTimeout() that resolve after different
time intervals, and print both results once both are completed.
Solution:
js
CopyEdit
let promise1 = new Promise(resolve
=> setTimeout(() => resolve("First Task Done"), 3000));
let promise2 = new Promise(resolve
=> setTimeout(() => resolve("Second Task Done"), 5000));
Promise.all([promise1,
promise2])
.then(results => {
console.log(results); // [ 'First Task Done', 'Second Task Done' ]
})
.catch(error => console.log(error));
Explanation:
- Promise.all()
waits for all promises in the array to resolve.
- It
resolves when both promises (promise1 and promise2) are completed,
printing the results in an array.
Assignment 5: Creating a
Chained Promise
Task:
Write a program that resolves a task and then chains another task after it is
completed.
Solution:
js
CopyEdit
let task1 = new Promise(resolve
=> setTimeout(() => resolve("Task 1 Complete"), 2000));
task1
.then(result => {
console.log(result); // Prints "Task 1 Complete"
return new Promise(resolve => setTimeout(()
=> resolve("Task 2 Complete"), 3000));
})
.then(result => {
console.log(result); // Prints "Task 2 Complete"
})
.catch(error => console.log(error));
Explanation:
- The
first promise resolves after 2 seconds, and then the .then() method chains
another promise that resolves after 3 seconds.
- Both
tasks are handled sequentially.
Assignment 6: Simulating
a Network Request with async/await
Task:
Simulate fetching data from an API with async/await, with a delay of 3 seconds.
Solution:
js
CopyEdit
async function fetchData()
{
console.log("Fetching data...");
let data = await new Promise(resolve => setTimeout(()
=> resolve("Fetched Data from API"), 3000));
console.log(data);
}
fetchData();
Explanation:
- The
fetchData() function simulates an API call by waiting 3 seconds using await.
- After
the delay, the result "Fetched Data from API" is logged.
Assignment 7: Using setInterval()
for Counting Down
Task:
Write a countdown timer using setInterval() that counts down from 10 to 0 and
then stops.
Solution:
js
CopyEdit
let count = 10;
let intervalId = setInterval(()
=> {
console.log(count);
count--;
if (count < 0) {
clearInterval(intervalId); // Stop countdown when count is less than 0
console.log("Countdown Finished");
}
}, 1000); // 1 second interval
Explanation:
- setInterval()
prints the value of count every second.
- The
countdown continues until count reaches 0, at which point the interval is
cleared.
Assignment 8: Handling
Error in Asynchronous Code with async/await
Task:
Create a function that simulates an asynchronous operation and handles an error
using async/await.
Solution:
js
CopyEdit
async function fetchDataWithError()
{
try {
let data = await new Promise((resolve,
reject) => setTimeout(() => reject("Error: Data Fetch Failed"),
2000));
console.log(data);
} catch (error) {
console.log(error); // Prints "Error: Data Fetch
Failed"
}
}
fetchDataWithError();
Explanation:
- The
fetchDataWithError() function simulates an error by rejecting the Promise.
- The
try/catch block handles the error and prints the error message.
Assignment 9: Chaining
Promises with Conditional Logic
Task:
Create a promise chain that checks a condition (whether a user is logged in)
and performs tasks based on that.
Solution:
js
CopyEdit
let isLoggedIn = true; // Change this to false to test the other
condition
let loginPromise = new Promise((resolve,
reject) => {
if (isLoggedIn) {
resolve("User Logged In");
} else {
reject("User Not Logged In");
}
});
loginPromise
.then(result => {
console.log(result); // Prints "User Logged In"
return "Access Granted";
})
.then(result => console.log(result)) // Prints "Access Granted"
.catch(error => console.log(error)); // Prints "User Not Logged In" if
false
Explanation:
- The
first promise checks if the user is logged in and resolves or rejects
accordingly.
- The
following .then() methods handle the results based on the outcome of the
initial check.
Assignment 10: Creating a
Timer with setTimeout() and Promise
Task:
Create a timer using setTimeout() wrapped in a Promise that resolves after 5
seconds.
Solution:
js
CopyEdit
function timer(seconds) {
return new Promise(resolve => {
setTimeout(() => {
resolve(`${seconds} seconds have passed`);
}, seconds * 1000);
});
}
timer(5)
.then(message => console.log(message)) // Prints "5 seconds have passed"
.catch(error => console.log(error));
Explanation:
- The
timer() function returns a Promise that resolves after a delay specified
by the seconds argument.
- After
5 seconds, the message is logged.
Conclusion:
These assignments provide
a wide range of tasks that help solidify your understanding of asynchronous
programming in Node.js. The use of setTimeout(), setInterval(), async/await,
and Promise helps you better handle real-world asynchronous tasks in Node.js,
making your applications more responsive and efficient.
4o mini
You said:
write 50 MCQs for the
concept above with explanation
ChatGPT said:
ChatGPT
Here are 50 Multiple
Choice Questions (MCQs) on the concept of Asynchronous Programming in
Node.js, including questions on setTimeout(), setInterval(), async/await,
and Promise. Each question comes with an explanation for the correct answer.
MCQ 1: What does the setTimeout()
function do in Node.js?
A) Executes code after a
specified time
B) Repeats code after a specified time
C) Sets a timer that cancels itself automatically
D) Executes code immediately
Answer:
A) Executes code after a specified time
Explanation: The setTimeout() function delays the execution of code by a
specified number of milliseconds.
MCQ 2: What is the
default behavior of setInterval() in Node.js?
A) It runs the provided
function once after a delay
B) It runs the provided function immediately
C) It runs the provided function repeatedly at specified intervals
D) It does nothing
Answer:
C) It runs the provided function repeatedly at specified intervals
Explanation: setInterval() executes a function repeatedly after a given
time interval, until it is stopped manually.
MCQ 3: What is the
purpose of the clearInterval() function in Node.js?
A) It stops a running
asynchronous function
B) It stops a set timeout
C) It cancels the repeating task set by setInterval()
D) It executes a function after a set delay
Answer:
C) It cancels the repeating task set by setInterval()
Explanation: clearInterval() is used to cancel an interval previously
set by setInterval().
MCQ 4: What does the async
keyword do in Node.js?
A) It defines a function
that returns a Promise
B) It pauses the function execution
C) It handles synchronous tasks
D) It does nothing
Answer:
A) It defines a function that returns a Promise
Explanation: The async keyword defines an asynchronous function that
always returns a Promise.
MCQ 5: What is the
purpose of the await keyword in Node.js?
A) It pauses the
execution of an asynchronous function until the Promise resolves
B) It checks if the Promise has resolved
C) It returns the result of an asynchronous operation
D) It executes a function immediately
Answer:
A) It pauses the execution of an asynchronous function until the Promise
resolves
Explanation: await is used to wait for a Promise to resolve inside an async
function.
MCQ 6: Which of the
following functions is asynchronous?
A) setTimeout()
B) setInterval()
C) async/await
D) All of the above
Answer:
D) All of the above
Explanation: setTimeout(), setInterval(), and async/await all handle
asynchronous operations in Node.js.
MCQ 7: Which of the
following returns a Promise in Node.js?
A) setTimeout()
B) setInterval()
C) async/await
D) new Promise()
Answer:
D) new Promise()
Explanation: new Promise() explicitly creates a new Promise in
JavaScript.
MCQ 8: What happens if
you use await outside of an async function?
A) It will throw an error
B) It will pause the function execution
C) It will resolve automatically
D) It will run synchronously
Answer:
A) It will throw an error
Explanation: await can only be used inside async functions. Using it
outside results in an error.
MCQ 9: What is the
default return value of an async function in Node.js?
A) A Promise
B) A string
C) An object
D) Undefined
Answer:
A) A Promise
Explanation: An async function always returns a Promise, which resolves
with the value returned from the function.
MCQ 10: How can you
handle errors in asynchronous functions using async/await?
A) Using a try/catch
block
B) Using throw
C) Using setTimeout()
D) Using clearInterval()
Answer:
A) Using a try/catch block
Explanation: Errors in asynchronous functions can be handled by wrapping
the await expressions in a try/catch block.
MCQ 11: What is the
purpose of chaining .then() in promises?
A) It handles synchronous
code
B) It handles multiple asynchronous operations
C) It waits for the first promise to resolve before executing the second
D) Both B and C
Answer:
D) Both B and C
Explanation: .then() allows you to chain asynchronous operations,
ensuring they execute in sequence once the previous promise resolves.
MCQ 12: How do you create
a new promise?
A) new Promise()
B) Promise.resolve()
C) Promise.reject()
D) new setTimeout()
Answer:
A) new Promise()
Explanation: A new Promise is created using new Promise() and takes a
function with two arguments: resolve and reject.
MCQ 13: How do you reject
a promise in Node.js?
A) Promise.reject()
B) reject()
C) Promise.resolve(false)
D) setTimeout(reject())
Answer:
B) reject()
Explanation: A promise can be rejected by calling reject() inside the
promise executor function.
MCQ 14: Which method is
used to wait for multiple promises to resolve in Node.js?
A) Promise.all()
B) Promise.set()
C) Promise.complete()
D) Promise.wait()
Answer:
A) Promise.all()
Explanation: Promise.all() waits for all promises in the array to
resolve and returns a new promise that resolves with an array of results.
MCQ 15: What will happen
if one of the promises in Promise.all() rejects?
A) All promises will
still resolve
B) It will stop and reject immediately
C) It will throw a warning
D) It will resolve the first rejected promise
Answer:
B) It will stop and reject immediately
Explanation: If any promise in Promise.all() rejects, the entire
operation is rejected and the error is propagated.
MCQ 16: What is the
return value of a setTimeout() function?
A) A Promise
B) An integer that represents the timeout ID
C) A string
D) An array
Answer:
B) An integer that represents the timeout ID
Explanation: setTimeout() returns a unique identifier for the timeout,
which can be used to cancel it later.
MCQ 17: How do you stop
an interval set by setInterval()?
A) clearTimeout()
B) clearInterval()
C) cancel()
D) stopInterval()
Answer:
B) clearInterval()
Explanation: clearInterval() is used to cancel an interval previously
set by setInterval().
MCQ 18: Which of the
following statements is true about asynchronous functions?
A) They always block the
main thread
B) They are executed synchronously
C) They are non-blocking and run in the background
D) They execute immediately after the event loop
Answer:
C) They are non-blocking and run in the background
Explanation: Asynchronous functions are non-blocking, meaning they allow
other operations to continue running while waiting for the result of the
asynchronous task.
**MCQ 19: What will the
following code snippet output?
js
CopyEdit
setTimeout(() => console.log("Hello"),
0);
console.log("World");
A) Hello
B) World
C) World Hello
D) Hello World
Answer:
C) World Hello
Explanation: The setTimeout() function schedules "Hello" to be
printed after the current execution stack completes, so "World" is
printed first.
MCQ 20: What is the
correct syntax for using async functions with await?
A) await function()
B) async function()
C) async function() { await expression; }
D) await async function()
Answer:
C) async function() { await expression; }
Explanation: An async function can contain await expressions to wait for
asynchronous operations to complete before moving to the next line.
MCQ 21: Which of the
following is a correct use of Promise.all()?
A) Promise.all([promise1,
promise2]).then(results => console.log(results))
B) Promise.all(promise1, promise2)
C) Promise.all()
D) Promise.all.then(promise1)
Answer:
A) Promise.all([promise1, promise2]).then(results => console.log(results))
Explanation: Promise.all() takes an array of promises and resolves when
all promises are successful.
MCQ 22: How do you handle
errors in promise chains?
A) try/catch
B) .catch()
C) .finally()
D) setTimeout()
Answer:
B) .catch()
Explanation: .catch() is used to handle any error that occurs in a
promise chain.
MCQ 23: What does Promise.resolve()
do?
A) It creates a resolved
Promise
B) It returns a pending promise
C) It rejects a promise
D) It pauses the program
Answer:
A) It creates a resolved Promise
Explanation: Promise.resolve() returns a Promise that is immediately
resolved with the given value.
MCQ 24: Which function is
commonly used to create a pending promise?
A) Promise.resolve()
B) new Promise()
C) Promise.all()
D) setInterval()
Answer:
B) new Promise()
Explanation: new Promise() creates a pending promise that can be
resolved or rejected later.
MCQ 25: What is the event
loop's role in asynchronous programming in Node.js?
A) It executes
synchronous code first
B) It schedules asynchronous code execution
C) It blocks the main thread
D) It runs in the background
Answer:
B) It schedules asynchronous code execution
Explanation: The event loop schedules and manages the execution of
asynchronous code, ensuring non-blocking operations.
I can continue writing
more questions if needed.
4o mini
You said:
yes
ChatGPT said:
ChatGPT
Here are the remaining 25
MCQs on asynchronous programming in Node.js:
MCQ 26: What is the
purpose of setTimeout() in asynchronous programming?
A) To execute a function
immediately
B) To delay the execution of a function by a specified time
C) To repeat the function execution periodically
D) To stop the execution of a function
Answer:
B) To delay the execution of a function by a specified time
Explanation: setTimeout() is used to delay the execution of a function
for a specified number of milliseconds.
MCQ 27: What happens when
an error occurs in a Promise?
A) The promise resolves
successfully
B) The promise enters a pending state
C) The promise is rejected
D) The promise is ignored
Answer:
C) The promise is rejected
Explanation: When an error occurs inside a promise, the promise is
rejected and the error is passed to the rejection handler.
MCQ 28: Which method is
used to handle a rejected promise?
A) .then()
B) .catch()
C) .finally()
D) .done()
Answer:
B) .catch()
Explanation: .catch() is used to handle any rejection in a promise.
MCQ 29: What will happen
if you use await with a non-Promise value?
A) It throws an error
B) It resolves immediately with the value
C) It creates a new promise
D) It pauses execution
Answer: B)
It resolves immediately with the value
Explanation: If await is used with a non-Promise value, it will resolve
immediately and return the value.
MCQ 30: Which of the
following is NOT true about promises?
A) Promises are always
asynchronous
B) Promises represent the result of an asynchronous operation
C) Promises can be either pending, resolved, or rejected
D) Promises are synchronous by default
Answer:
D) Promises are synchronous by default
Explanation: Promises are always asynchronous, meaning they resolve or
reject in the future, not immediately.
MCQ 31: What does the finally()
method do in a Promise chain?
A) It handles success
cases
B) It handles errors
C) It executes a block of code regardless of the Promise's outcome
D) It cancels the promise
Answer:
C) It executes a block of code regardless of the Promise's outcome
Explanation: .finally() is used to execute cleanup code after the
promise resolves or rejects.
**MCQ 32: What does the await
keyword do in the following code?
js
CopyEdit
let result = await fetchData();
A) It stops the function
and runs the next line of code
B) It waits for the fetchData() promise to resolve
C) It immediately runs fetchData()
D) It handles errors in the promise
Answer:
B) It waits for the fetchData() promise to resolve
Explanation: await pauses the execution until the fetchData() promise
resolves.
MCQ 33: How would you
handle multiple asynchronous operations in parallel using promises?
A) Promise.all()
B) setTimeout()
C) setInterval()
D) async/await
Answer:
A) Promise.all()
Explanation: Promise.all() is used to handle multiple promises in
parallel, ensuring they all resolve before proceeding.
**MCQ 34: What will the
following code output?
js
CopyEdit
let promise = new Promise((resolve,
reject) => {
resolve("Success!");
});
promise.then(result =>
console.log(result));
A) Success!
B) Error
C) undefined
D) It will throw an exception
Answer:
A) Success!
Explanation: The promise resolves with the value "Success!"
and it is logged using .then().
MCQ 35: What is the
return type of a function that is marked as async?
A) String
B) Number
C) A Promise
D) Undefined
Answer:
C) A Promise
Explanation: An async function always returns a Promise, even if it
returns a value directly.
MCQ 36: Which of the
following methods is used to create a resolved promise with a value?
A) new Promise()
B) Promise.resolve()
C) Promise.catch()
D) Promise.all()
Answer:
B) Promise.resolve()
Explanation: Promise.resolve() creates a promise that is immediately
resolved with the given value.
**MCQ 37: What is the
output of the following code?
js
CopyEdit
setTimeout(() => console.log("First"),
0);
setTimeout(() => console.log("Second"),
0);
console.log("Third");
A) First Second Third
B) Third First Second
C) Third Second First
D) It will throw an error
Answer:
C) Third Second First
Explanation: console.log("Third") executes immediately, while
the setTimeout() functions are scheduled to run after the current execution
stack completes.
MCQ 38: What happens if a
promise is not handled (i.e., no .then() or .catch())?
A) The promise will
automatically resolve
B) The promise will be ignored
C) The promise will be rejected silently
D) It will throw an error
Answer:
C) The promise will be rejected silently
Explanation: If a promise is not handled, it can silently fail
(especially in the case of rejection), but Node.js will issue a warning if the
promise rejection is not caught.
MCQ 39: What happens if
you use setInterval() with a delay of 0?
A) It runs immediately
B) It executes the function once
C) It runs the function repeatedly with a 0ms delay
D) It causes an infinite loop
Answer:
C) It runs the function repeatedly with a 0ms delay
Explanation: Setting the delay to 0ms will cause the function to execute
repeatedly as quickly as possible, subject to other event loop operations.
MCQ 40: Which of the
following will correctly handle an error in an asynchronous operation?
A) async function() {
await someFunction(); }
B) async function() { try { await someFunction(); } catch(error) {
console.log(error); } }
C) await function() { someFunction(); }
D) setTimeout(() => { throw new Error(); })
Answer:
B) async function() { try { await someFunction(); } catch(error) {
console.log(error); } }
Explanation: The try/catch block inside an async function is used to
handle errors that occur with await.
MCQ 41: Which of the
following is true about Promise.all()?
A) It executes promises
sequentially
B) It executes all promises in parallel
C) It resolves when any promise resolves
D) It executes only the first promise in the list
Answer:
B) It executes all promises in parallel
Explanation: Promise.all() executes promises in parallel and resolves
when all promises in the array resolve.
MCQ 42: What happens if a
promise is rejected after Promise.all() has been called?
A) The other promises
will continue to execute
B) It cancels all promises in the array
C) It resolves all promises anyway
D) It resolves only the first promise
Answer:
B) It cancels all promises in the array
Explanation: If any promise is rejected, Promise.all() immediately
rejects, canceling all other promises in the array.
MCQ 43: Which method is
used to make a Promise wait for a condition to be met before continuing?
A) Promise.resolve()
B) Promise.delay()
C) Promise.wait()
D) Promise.then()
Answer:
D) Promise.then()
Explanation: .then() is used to handle the result of a promise when it
resolves, and it allows the execution of further code after the promise is
resolved.
**MCQ 44: What is the
output of the following code?
js
CopyEdit
let promise1 = Promise.resolve(3);
let promise2 = Promise.resolve(5);
Promise.all([promise1,
promise2]).then(console.log);
A) 3
B) 5
C) [3, 5]
D) Error
Answer:
C) [3, 5]
Explanation: Promise.all() returns an array of resolved values from the
promises, which in this case are [3, 5].
MCQ 45: Which of the
following is NOT a valid state of a Promise?
A) Pending
B) Fulfilled
C) Rejected
D) Finished
Answer:
D) Finished
Explanation: Promises can be in one of three states: Pending, Fulfilled,
or Rejected. "Finished" is not a valid state.
MCQ 46: What does the async
keyword do when used with a function?
A) It makes the function
synchronous
B) It makes the function return a Promise
C) It pauses the function execution
D) It runs the function immediately
Answer:
B) It makes the function return a Promise
Explanation: When a function is marked as async, it implicitly returns a
Promise, even if no promise is explicitly returned.
MCQ 47: Which of the
following will allow you to pause the execution of an asynchronous function?
A) await
B) setTimeout()
C) setInterval()
D) Promise.all()
Answer:
A) await
Explanation: await is used to pause the execution of an async function
until the promise is resolved.
MCQ 48: Which of the
following can be used to handle multiple asynchronous operations in sequence?
A) Promise.all()
B) Promise.race()
C) async/await
D) setInterval()
Answer:
C) async/await
Explanation: async/await allows handling multiple asynchronous
operations in sequence by pausing execution until the promise is resolved.
**MCQ 49: What will the
following code output?
js
CopyEdit
console.log("Start");
setTimeout(() => console.log("Inside
Timeout"), 0);
console.log("End");
A) Start End Inside
Timeout
B) Inside Timeout Start End
C) Start Inside Timeout End
D) Inside Timeout End Start
Answer:
A) Start End Inside Timeout
Explanation: setTimeout() is asynchronous, so "Inside Timeout"
will be logged after the synchronous code finishes execution.
MCQ 50: Which function
allows you to cancel a setTimeout()?
A) clearInterval()
B) clearTimeout()
C) cancelTimeout()
D) stopTimeout()
Answer:
B) clearTimeout()
Explanation: clearTimeout() is used to cancel a previously scheduled setTimeout().
This completes the set of
50 MCQs on asynchronous programming in Node.js!

No comments:
Post a Comment