uiz Space

May 2025 term · Modern Application Development II · BSCS2006

Modern Application Development II End Term: 31 August 2025, Set QIB3 (May 2025 term)

The IIT Madras BS Modern Application Development II (MAD 2) End Term paper sat on 31 Aug 2025, in the May 2025 term, set QIB3: 32 questions for 100 marks in 180 minutes. Every question is below with its answer. Take it as a timed mock test to be marked, or read it through first.

Questions
32
Marks
100
Duration
180 min
MCQ
21
MSQ
11

Updated

Official paper: IIT M IMPROVEMENT AN EXAM QIB3 31 Aug 2025 · No negative marking.

Question 1

+2 marksOne correct option

In a message queue system, if the consumer is slower than the producer, what is likely to occur first?

  1. A

    Messages will be dropped

  2. B

    Messages will accumulate in the queue

  3. C

    The consumer will speed up automatically

  4. D

    The producer will block until the consumer is ready

Show answer

Correct answer

  • B

    Messages will accumulate in the queue

Question 2

+2 marksOne correct option

What does "reactivity" mean in the context of frontend frameworks like Vue.js?

  1. A

    The component will reload when data changes

  2. B

    All function calls become asynchronous

  3. C

    It disables direct access to state

  4. D

    The DOM updates automatically when the underlying reactive data changes

Show answer

Correct answer

  • D

    The DOM updates automatically when the underlying reactive data changes

Question 3

+2 marksOne correct option

In Flask, what is the main benefit of using the @cache.cached() decorator?

  1. A

    It stores output in session storage

  2. B

    It enables token authentication

  3. C

    It sends compressed response headers

  4. D

    It skips route execution for repeated inputs

Show answer

Correct answer

  • D

    It skips route execution for repeated inputs

Question 4

+2 marksOne correct option

What is the primary purpose of CORS (Cross-Origin Resource Sharing)?

  1. A

    To encrypt data between client and server

  2. B

    To compress HTTP responses

  3. C

    To authenticate users across applications

  4. D

    To control which domains can access resources

Show answer

Correct answer

  • D

    To control which domains can access resources

Question 5

+2 marksOne or more correct options

Which of the following practices help protect against supply chain attacks?

Select all that apply.

  1. A

    Storing keys only in environment variables

  2. B

    Version pinning

  3. C

    Using only packages with over 1000 stars on GitHub

  4. D

    Reduce Dependencies

Show answer

Correct answers

  • B

    Version pinning

  • D

    Reduce Dependencies

Question 6

+2 marksOne or more correct options

Which of the following factors directly affect the speed and performance of a web page load?

Select all that apply.

  1. A

    The number of CSS selectors in the stylesheet

  2. B

    Use of semantic HTML tags

  3. C

    Number of HTTP requests made

  4. D

    File size of resources (like images, JS)

Show answer

Correct answers

  • C

    Number of HTTP requests made

  • D

    File size of resources (like images, JS)

Question 7

+2 marksOne or more correct options

Which of the following is/are the potential benefits of using a message broker?

Select all that apply.

  1. A

    A message broker makes the network scalable for adding more servers to the network.

  2. B

    A message broker allows two servers in a network to directly communicate with each other, without an intermediary.

  3. C

    A message broker is not suited in case of traffic spikes, as messages are retained in the queue until processed.

  4. D

    A message broker can be used for batch processing of messages.

Show answer

Correct answers

  • A

    A message broker makes the network scalable for adding more servers to the network.

  • D

    A message broker can be used for batch processing of messages.

Question 8

+2 marksOne or more correct options

Which statements about webhooks are correct?

Select all that apply.

  1. A

    They enable real-time data delivery

  2. B

    They use HTTP POST requests typically

  3. C

    They're designed for server-to-server communication

  4. D

    They require polling from the client

Show answer

Correct answers

  • A

    They enable real-time data delivery

  • B

    They use HTTP POST requests typically

  • C

    They're designed for server-to-server communication

Question 9

+3 marksOne correct option

A popular e-commerce platform needs to notify multiple third-party services (inventory management, email marketing, analytics) whenever a customer places an order. The development team is considering different approaches to handle these notifications.
Scenario: When an order is placed, the system needs to:
● Update inventory levels in an external warehouse system
● Send a welcome email through a third-party email service
● Log analytics data to an external tracking service
● Update customer loyalty points in a CRM system
Which of the following statements about using webhooks for this scenario is MOST accurate?

  1. A

    Webhooks are not suitable for this use case because they require the e- commerce platform to continuously poll each third-party service to check if they're ready to receive data, which would create unnecessary network overhead.

  2. B

    Webhooks should be avoided in this scenario because they operate synchronously, meaning the customer's order placement would be delayed until all third-party services have successfully processed their notifications.

  3. C

    Webhooks provide an ideal solution as they allow the e-commerce platform to push real-time notifications to all subscribed third-party services immediately when an order is placed, eliminating the need for these services to repeatedly poll for updates.

  4. D

    Webhooks are primarily designed for read-only operations and cannot handle complex data payloads like order information, making them unsuitable for e-commerce transaction notifications.

Show answer

Correct answer

  • C

    Webhooks provide an ideal solution as they allow the e-commerce platform to push real-time notifications to all subscribed third-party services immediately when an order is placed, eliminating the need for these services to repeatedly poll for updates.

Question 10

+3 marksOne correct option

What is the main advantage of using caching in a Flask-based web application?

  1. A

    It eliminates the need for client-side rendering

  2. B

    It reduces server load by reusing responses for repeated requests

  3. C

    It encrypts data transmission between server and client

  4. D

    It avoids the need for database interactions completely

Show answer

Correct answer

  • B

    It reduces server load by reusing responses for repeated requests

Question 11

+3 marksOne correct option

What will be the order of console output when the following JavaScript code is executed?

javascript
async function test() {
console.log("P");
await Promise.resolve();
console.log("Q");
}
console.log("R");
test();
console.log("S");
  1. A

    R P Q S

  2. B

    P R S Q

  3. C

    R S P Q

  4. D

    R P S Q

Show answer

Correct answer

  • D

    R P S Q

Question 12

+3 marksOne correct option

Consider the following JavaScript program:

javascript
const user = {
name: 'Alice',
age: 25,
city: 'Boston',
country: 'USA'
};
const { name, city, ...otherInfo } = user;
const newUser = { name, location: city, ...otherInfo };
console.log(name);
console.log(otherInfo);
console.log(newUser);

What will be the output of the above program?

  1. A
  2. B
  3. C
  4. D
Show answer

Correct answer

  • C

Question 13

+3 marksOne correct option

Consider the following javascript program.

javascript
new Promise((resolve, reject) => {
const score = 0.45;
if (score >= 0.5) {
resolve(score);
} else {
reject(new Error("Score too low"));
}
})
.then(data => {
console.log("Stage A:", data);
return data * 10;
})
.catch(error => {
console.log("Stage B:", error.message);
return 3;
})
.then(data => {
console.log("Stage C:", data);
if (data < 5) {
throw new Error("Value below threshold");
}
return data + 2;
})
.then(data => {
console.log("Stage D:", data);
return data / 2;
})
.catch(error => {
console.log("Stage E:", error.message);
if (error.message === "Value below threshold") {
return "Recovered";
}
throw error;
})
.then(data => {
console.log("Stage F:", data);
if (data === "Recovered") {
return 10;
}
return data * 4;
})
.finally(() => {
console.log("Stage G: Cleanup completed");
});

What will be the output of the above program on the browser’s console?

  1. A
  2. B
  3. C
  4. D
Show answer

Correct answer

  • B

Question 14

+3 marksOne correct option

Consider this HTML and Vue setup:

index.html

html
<div id="app1">{{ message }}</div>
<div id="app2">{{ message }}</div>
<script src="app.js" />

app.js

javascript
new Vue({
el: '#app1',
data: { message: 'Hello from App 1' }
});
new Vue({
el: '#app2',
data: { message: 'Hello from App 2' }
});

What will be rendered on the browser?

  1. A

    App 1 only shows data

  2. B

    Both show “Hello from App 2”

  3. C

    Both show “Hello from App 1”

  4. D

    Each renders its own message independently

Show answer

Correct answer

  • D

    Each renders its own message independently

Question 15

+3 marksOne correct option

Consider the following JavaScript code running in a browser:

javascript
localStorage.setItem('score', '10');
sessionStorage.setItem('multiplier', '3');
for (let i = 0; i < 2; i++) {
let score = localStorage.getItem('score');
let multiplier = sessionStorage.getItem('multiplier');
score = score + 5;
multiplier = multiplier * 2;
localStorage.setItem('score', score);
sessionStorage.setItem('multiplier', multiplier);
}
console.log(localStorage.getItem('score'));
console.log(sessionStorage.getItem('multiplier'));

What will be the output in the browser console?

  1. A
  2. B
  3. C
  4. D
Show answer

Correct answer

  • D

Question 16

+3 marksOne or more correct options

Which factors directly impact the Lighthouse "Performance" score?

Select all that apply.

  1. A

    First Contentful Paint (FCP)

  2. B

    Time to Interactive (TTI)

  3. C

    Layout Shift

  4. D

    HTTPS usage

Show answer

Correct answers

  • A

    First Contentful Paint (FCP)

  • B

    Time to Interactive (TTI)

  • C

    Layout Shift

Question 17

+3 marksOne or more correct options

Which statements are true about handling background tasks in Flask with Celery?

Select all that apply.

  1. A

    Using time.sleep() blocks the event loop and is recommended for async tasks

  2. B

    Celery allows long-running tasks to be executed asynchronously

  3. C

    Polling is a strategy to check task status periodically

  4. D

    Flask + Celery + Redis is a common stack for async task management

Show answer

Correct answers

  • B

    Celery allows long-running tasks to be executed asynchronously

  • C

    Polling is a strategy to check task status periodically

  • D

    Flask + Celery + Redis is a common stack for async task management

Question 18

+3 marksOne or more correct options

Which of the following are true about mutations and actions in Vuex?

Select all that apply.

  1. A

    Actions can be asynchronous

  2. B

    Only actions can call APIs through fetch call

  3. C

    Mutations should modify state directly

  4. D

    Mutations can be asynchronous

Show answer

Correct answers

  • A

    Actions can be asynchronous

  • B

    Only actions can call APIs through fetch call

  • C

    Mutations should modify state directly

Question 19

+3 marksOne or more correct options

Select all that apply.

  1. A

    The class "active" will only be applied to the div element if the variable "isActive" evaluates to true.

  2. B

    The class "disabled" will be applied to the div element when the variable "isEnabled" evaluates to false.

  3. C

    The class "text-bold" will always be applied to the div element regardless of the "hasBoldText" variable value.

  4. D

    All three classes ("active", "text-bold", "disabled") will always be applied to the div element.

  5. E

    If "isEnabled" is undefined, the "disabled" class will not be applied to the div element.

  6. F

    The class "text-bold" will only be applied if the variable "hasBoldText" exists and evaluates to a truthy value.

Show answer

Correct answers

  • A

    The class "active" will only be applied to the div element if the variable "isActive" evaluates to true.

  • B

    The class "disabled" will be applied to the div element when the variable "isEnabled" evaluates to false.

  • F

    The class "text-bold" will only be applied if the variable "hasBoldText" exists and evaluates to a truthy value.

Question 20

+3 marksOne correct option

Given the following component setup, answer the given subquestions

Component: Task.vue

html
<template>
<div>
<button @click="toggleShowCompleted">
{{ showCompleted ? 'Hide' : 'Show' }} Completed
</button>
<ul>
<li v-for="task in filteredTasks" :key="task.id">
<span>{{ task.name }} - {{ task.status }}</span>
<button @click="markComplete(task.id)">Mark Complete</button>
</li>
</ul>
<p>Total Completed: {{ completedCount }}</p>
</div>
</template>
<script>
export default {
data() {
return {
showCompleted: false,
tasks: [
{ id: 1, name: 'Learn Vue', status: 'incomplete' },
{ id: 2, name: 'Build Project', status: 'incomplete' },
{ id: 3, name: 'Test App', status: 'complete' }
]
}
;
html
},
computed: {
filteredTasks() {
if (this.showCompleted) return this.tasks;
return this.tasks.filter(function (task) {
return task.status !== 'complete';
});
},
completedCount() {
return this.tasks.reduce(function (acc, task) {
return acc + (task.status === 'complete' ? 1 : 0);
}, 0);
}
},
methods: {
markComplete(id) {
const task = this.tasks.find(function (t) {
return t.id === id;
});
if (task && task.status === 'incomplete') {
task.status = 'complete';
}
},
toggleShowCompleted() {
this.showCompleted = !this.showCompleted;
}
}
};
</script>

Scenario
1. The component is loaded.
2. User clicks "Mark Complete" for the task named Build Project.
3. User clicks "Show Completed" button again.

After step 2 (Mark Completed is clicked), what tasks are shown?

  1. A

    Learn Vue

  2. B

    Learn Vue, Build Project, Test App

  3. C

    Test App only

  4. D

    None

Show answer

Correct answer

  • A

    Learn Vue

Question 21

+3 marksOne correct option

Given the following component setup, answer the given subquestions

Component: Task.vue

html
<template>
<div>
<button @click="toggleShowCompleted">
{{ showCompleted ? 'Hide' : 'Show' }} Completed
</button>
<ul>
<li v-for="task in filteredTasks" :key="task.id">
<span>{{ task.name }} - {{ task.status }}</span>
<button @click="markComplete(task.id)">Mark Complete</button>
</li>
</ul>
<p>Total Completed: {{ completedCount }}</p>
</div>
</template>
<script>
export default {
data() {
return {
showCompleted: false,
tasks: [
{ id: 1, name: 'Learn Vue', status: 'incomplete' },
{ id: 2, name: 'Build Project', status: 'incomplete' },
{ id: 3, name: 'Test App', status: 'complete' }
]
}
;
html
},
computed: {
filteredTasks() {
if (this.showCompleted) return this.tasks;
return this.tasks.filter(function (task) {
return task.status !== 'complete';
});
},
completedCount() {
return this.tasks.reduce(function (acc, task) {
return acc + (task.status === 'complete' ? 1 : 0);
}, 0);
}
},
methods: {
markComplete(id) {
const task = this.tasks.find(function (t) {
return t.id === id;
});
if (task && task.status === 'incomplete') {
task.status = 'complete';
}
},
toggleShowCompleted() {
this.showCompleted = !this.showCompleted;
}
}
};
</script>

Scenario
1. The component is loaded.
2. User clicks "Mark Complete" for the task named Build Project.
3. User clicks "Show Completed" button again.

After step 3 (Mark Complete is clicked on Build Project), how many completed tasks are reported in the UI?

  1. A

    1

  2. B

    2

  3. C

    3

  4. D

    0

Show answer

Correct answer

  • B

    2

Question 22

+3 marksOne or more correct options

Given the following component setup, answer the given subquestions

Component: Task.vue

html
<template>
<div>
<button @click="toggleShowCompleted">
{{ showCompleted ? 'Hide' : 'Show' }} Completed
</button>
<ul>
<li v-for="task in filteredTasks" :key="task.id">
<span>{{ task.name }} - {{ task.status }}</span>
<button @click="markComplete(task.id)">Mark Complete</button>
</li>
</ul>
<p>Total Completed: {{ completedCount }}</p>
</div>
</template>
<script>
export default {
data() {
return {
showCompleted: false,
tasks: [
{ id: 1, name: 'Learn Vue', status: 'incomplete' },
{ id: 2, name: 'Build Project', status: 'incomplete' },
{ id: 3, name: 'Test App', status: 'complete' }
]
}
;
html
},
computed: {
filteredTasks() {
if (this.showCompleted) return this.tasks;
return this.tasks.filter(function (task) {
return task.status !== 'complete';
});
},
completedCount() {
return this.tasks.reduce(function (acc, task) {
return acc + (task.status === 'complete' ? 1 : 0);
}, 0);
}
},
methods: {
markComplete(id) {
const task = this.tasks.find(function (t) {
return t.id === id;
});
if (task && task.status === 'incomplete') {
task.status = 'complete';
}
},
toggleShowCompleted() {
this.showCompleted = !this.showCompleted;
}
}
};
</script>

Scenario
1. The component is loaded.
2. User clicks "Mark Complete" for the task named Build Project.
3. User clicks "Show Completed" button again.

Which of the following are true about this component’s behavior?

Select all that apply.

  1. A
  2. B
  3. C
  4. D
Show answer

Correct answers

  • C
  • D

Question 23

+4.5 marksOne correct option

Consider the following JavaScript code:

javascript
const globalVar = 100;
var value = 200;
const calculator = {
value: 50,
compute: function() {
const innerObj = {
value: 25,
regularMethod: function() {
return this.value;
},
arrowMethod: () => {
return this.value;
},
mixedMethod: function() {
const arrowInside = () => this.value;
return arrowInside();
}
};
return {
regular: innerObj.regularMethod(),
arrow: innerObj.arrowMethod(),
mixed: innerObj.mixedMethod()
};
}
};
const result = calculator.compute();
console.log(result.regular);
console.log(result.arrow);
console.log(result.mixed);

Assuming this code runs in a browser environment, what will be the output?

  1. A
  2. B
  3. C
  4. D
Show answer

Correct answer

  • B

Question 24

+4.5 marksOne correct option

Consider this Vue.js component code:

javascript
const TodoApp = {
template: `
<div>
<input v-model="newTodo" @keyup.enter="addTodo" />
<ul>
<li v-for="todo in todos" :key="todo.id">{{ todo.text }}</li>
</ul>
</div>
`,
data() {
return {
newTodo: '',
todos: []
}
},
methods: {
addTodo() {
if (this.newTodo) {
this.todos.push({ id: Date.now(), text: this.newTodo });
this.newTodo = '';
}
}
}
}

What happens when a user types "Learn Vue" into the input field and presses Enter?

Note: The @keyup.enter directive calls addTodo() when the Enter key is pressed.

  1. A
  2. B
  3. C
  4. D
Show answer

Correct answer

  • B

Question 25

+4.5 marksOne correct option

Given this Vue Router setup:

javascript
const routes = [
{ path: '/user/:id/profile', component: UserProfile },
{ path: '/user/:id', component: User },
{ path: '*', component: NotFound },
{ path: '/user/:id/settings', component: UserSettings },
];

What component renders for URL /user/123/settings?

  1. A

    UserProfile

  2. B

    User

  3. C

    NotFound

  4. D

    UserSettings

Show answer

Correct answer

  • C

    NotFound

Question 26

+4.5 marksOne correct option

Given the Flask app:

python
from flask import Flask
from flask_cors import CORS
app = Flask(__name__)
CORS(app, resources={r"/api/*": {"origins": "http://localhost:3000"}})
@app.route('/api/data')
def data():
return {"msg": "Success"}

frontend code:

javascript
fetch("http://localhost:5000/api/data")
.then(res => res.json())
.then(data => console.log(data));

What will happen when run from a Vue app hosted at http://localhost:5173?

  1. A

    Request succeeds

  2. B

    CORS error occurs

  3. C

    404 error

  4. D

    The server crashes

Show answer

Correct answer

  • B

    CORS error occurs

Question 27

+4.5 marksOne correct option

What will this JavaScript code output?

javascript
function createCounter() {
let count = 0;
return function() {
count++;
return count;
};
}
const counter1 = createCounter();
const counter2 = createCounter();
console.log(counter1());
console.log(counter1());
console.log(counter2());
  1. A
  2. B
  3. C
  4. D
Show answer

Correct answer

  • B

Question 28

+4.5 marksOne or more correct options

Consider the following Vue component structure with nested components and complex slot configurations:

javascript
Vue.component('data-provider', {
template: `
<div class="provider">
<slot name="header" :user="currentUser" :loading="isLoading"></slot>
<slot name="content" :items="filteredItems" :count="itemCount"></slot>
<slot :fallback="defaultMessage" :error="errorState"></slot>
</div>
`,
data() {
return {
currentUser: { name: 'John', role: 'admin' },
isLoading: false,
filteredItems: ['item1', 'item2', 'item3'],
itemCount: 3,
defaultMessage: 'No data available',
errorState: null
}
}
});
Vue.component('parent-component', {
template: `
<data-provider>
<template v-slot:header="{ user, loading }">
<h1 v-if="!loading">Welcome {{ user.name }}</h1>
<span v-else>Loading...</span>
</template>
<template v-slot:content="slotProps">
<ul>
<li v-for="item in slotProps.items" :key="item">
{{ item }} ({{ slotProps.count }} total)
</li>
</ul>
</template>
<template v-slot:default="defaultProps">
<p>{{ defaultProps.fallback }}</p>
</template>
</data-provider>
`
});

Now consider this usage of the parent-component:

html
<div id="app">
<parent-component></parent-component>
</div>

Assuming that the root Vue instance has already been created and mounted to div app. Which of the following statements are CORRECT?

Select all that apply.

  1. A

    The header slot will display "Welcome John" when loading is true

  2. B

    The content slot will render 3 list items with "item1 (3 total)", "item2 (3 total)", "item3 (3 total)"

  3. C

    The default slot will display "No data available" from the fallback prop

  4. D

    If we change isLoading: true in data-provider, the header will show "Loading..."

  5. E

    Changing v-slot:default to just v-slot in parent-component would break the functionality

Show answer

Correct answers

  • B

    The content slot will render 3 list items with "item1 (3 total)", "item2 (3 total)", "item3 (3 total)"

  • C

    The default slot will display "No data available" from the fallback prop

  • D

    If we change isLoading: true in data-provider, the header will show "Loading..."

Question 29

+4.5 marksOne correct option

Answer the given Subquestions:

Consider the following Vue Router configuration in a Vue 2 application:

javascript
const routes = [
{
path: '/',
name: 'Home',
component: HomeView
},
{
path: '/user/:id',
name: 'UserProfile',
component: UserProfile
},
{
path: '/product/:category/:id',
name: 'ProductDetail',
component: ProductDetail
}
];

In a Vue component, you have these navigation methods:

html
<template>
<div>
<button @click="goToUser">View User</button>
<button @click="goToProduct">View Product</button>
<router-link :to="{ name: 'Home' }">Home</router-link>
</div>
</template>
<script>
export default {
methods: {
goToUser() {
this.$router.push({ name: 'UserProfile', params: { id: 123 } });
},
goToProduct() {
this.$router.push({ name: 'ProductDetail',
params: { category: 'electronics', id: 456}
});
},
navigateOne() {
this.$router.push({ name: 'UserProfile', params: { id: 555 },
query: { tab: 'settings'}
});
},
navigateTwo() {
this.$router.replace({ name: 'Home' });
},
goBack() {
this.$router.go(-1);
}
}
</script>

What URLs will be generated when the user clicks each navigation element?

  1. A

    User button: /user,
    Product button: /product,
    Home link: /home

  2. B

    User button: /user/123,
    Product button: /product/electronics/456,
    Home link: /

  3. C

    User button: /UserProfile/123,
    Product button: /ProductDetail/electronics/456,
    Home link: /Home

  4. D

    User button: /user?id=123,
    Product button: /product?category=electronics&id=456,
    Home link: /

Show answer

Correct answer

  • B

    User button: /user/123,
    Product button: /product/electronics/456,
    Home link: /

Question 30

+4.5 marksOne or more correct options

Answer the given Subquestions:

Using the same Vue Router configuration from the previous question, Select ALL correct statements about these navigation methods.

Select all that apply.

  1. A

    The "View User" link will navigate to /user/789 and match the UserProfile route

  2. B

    The navigateOne() method will create URL /user/555?tab=settings

  3. C

    The $router.replace() method adds a new entry to the browser history

  4. D

    The $router.go(-1) method navigates to the previous page in browser history

Show answer

Correct answers

  • B

    The navigateOne() method will create URL /user/555?tab=settings

  • D

    The $router.go(-1) method navigates to the previous page in browser history

Question 31

+3 marksOne correct option

Prashant and Nikita are creating a quiz question paper collaboratively. They are each working on different sections — and complete their tasks in parallel. Meanwhile, Mayur is enjoying a single- player game that finishes when the game loop ends.
To compare productivity:
● If Prashant and Nikita (together) finish faster than Mayur, the winner is "Team".
● If Mayur finishes faster, he wins.
● If both take the same time, Mayur wins by default.
You are simulating this scenario in the browser.Prashant and Nikita are represented using parallel Promises. Mayur is represented using a single Promise. The frontend must calculate who finishes first using asynchronous logic, and display the result.

app.js

javascript
function simulateTasks() {
const prashant = new Promise(resolve => setTimeout(() =>
resolve("Prashant"), 3000));
const nikita = new Promise(resolve => setTimeout(() =>
resolve("Nikita"), 2000));
const mayur = new Promise(resolve => setTimeout(() =>
resolve("Mayur"), 4000));
const team = Promise.all([prashant, nikita]).then(() =>
"Team");
Promise.race([team, mayur]).then(winner => {
console.log("Winner is:", winner);
});
}

Based on the above data, answer the given subquestions.

If Prashant and Nikita finish together in 3 seconds (since Promise.all waits for both), and Mayur finishes in 4 seconds, who wins?

  1. A

    Mayur

  2. B

    Team

  3. C

    Nikita

  4. D

    Race condition prevents output

Show answer

Correct answer

  • B

    Team

Question 32

+3 marksOne correct option

Prashant and Nikita are creating a quiz question paper collaboratively. They are each working on different sections — and complete their tasks in parallel. Meanwhile, Mayur is enjoying a single- player game that finishes when the game loop ends.
To compare productivity:
● If Prashant and Nikita (together) finish faster than Mayur, the winner is "Team".
● If Mayur finishes faster, he wins.
● If both take the same time, Mayur wins by default.
You are simulating this scenario in the browser.Prashant and Nikita are represented using parallel Promises. Mayur is represented using a single Promise. The frontend must calculate who finishes first using asynchronous logic, and display the result.

app.js

javascript
function simulateTasks() {
const prashant = new Promise(resolve => setTimeout(() =>
resolve("Prashant"), 3000));
const nikita = new Promise(resolve => setTimeout(() =>
resolve("Nikita"), 2000));
const mayur = new Promise(resolve => setTimeout(() =>
resolve("Mayur"), 4000));
const team = Promise.all([prashant, nikita]).then(() =>
"Team");
Promise.race([team, mayur]).then(winner => {
console.log("Winner is:", winner);
});
}

Based on the above data, answer the given subquestions.

app2.js

javascript
async function playGame() {
const start = Date.now();
const prashantPromise = new Promise(resolve => setTimeout(resolve, 3000));
const nikitaPromise = new Promise(resolve => setTimeout(resolve, 2000));
const mayurPromise = new Promise(resolve => setTimeout(resolve, 2000));
await Promise.all([prashantPromise, nikitaPromise]);
const teamTime = Date.now() - start;
await mayurPromise;
const mayurTime = Date.now() - start;
const winner = (teamTime < mayurTime) ? "Team" : "Mayur";
console.log(`Winner is: ${winner}`);
}

The Team takes 5 seconds in total. Mayur takes 2 seconds. According to the logic of app2.js, who is the winner?

  1. A

    Mayur

  2. B

    Team

  3. C

    Undefined

  4. D

    Error due to async logic

Show answer

Correct answer

  • A

    Mayur