Promises, Callbacks, async/await Flashcards

1
Q

What is a callback in JavaScript

A

A function passed as an argument to another function and executed later after work completes or an event occurs.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Why are callbacks used in JavaScript

A

To handle asynchronous tasks without blocking the single-threaded execution.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How do callbacks work in JavaScript

A

A function is passed as an argument to another function which executes it when appropriate such as after completing its work.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What are the two types of callbacks

A

Synchronous callbacks executed immediately and asynchronous callbacks executed after async operations.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What analogy explains callbacks

A

Giving a phone number to a restaurant which calls back when the order is ready.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is a synchronous callback example

A

A function passed to another function and executed right away like logging a greeting then a goodbye.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is an asynchronous callback example

A

Using setTimeout to delay executing a function after data fetching as simulated with a timer.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How do callback functions differ from regular functions

A

Callbacks are passed as arguments and rely on another function to execute them while regular functions are called directly.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is callback hell

A

Nested callbacks leading to complex and hard-to-read code often fixed with Promises or Async-Await.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What are solutions to callback hell

A

Using Promises for cleaner async code or Async-Await to make it look synchronous.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is a key point about callbacks

A

They are essential for non-blocking operations in JavaScript and avoiding callback hell with modern syntax.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

How is a callback used for error handling in Node.js

A

Callbacks often follow the error-first pattern like function(err data) where err is checked before processing data.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is a common array method using a callback

A

The forEach method takes a callback to execute on each element like
[1 2 3].forEach(num =>
console.log(num)
)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

How can you pass an anonymous function as a callback

A

Pass a function directly as an argument like

          setTimeout(() => 
                   console.log('Done') 
               ,1000)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is an example of a callback with parameters

A

Using

addEventListener(‘click’ (event) => console.log(event.target))

to log the clicked element.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

How do you convert a synchronous callback to async

A

Use setTimeout to delay execution like callback => setTimeout(() => callback() 0).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What is a problem with nested callbacks

A

Deeply nested code like
step1(() => step2(() => step3()))
becomes hard to read and maintain.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

How do Promises replace callbacks

A

Promises chain .then() methods like

fetch(url).then(data => console.log(data)).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What is an example of callback-based file reading in Node.js

A

fs.readFile(‘file.txt’, ‘utf8’,
(err, data) => {
if (err) throw err; console.log(data) }
)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

How to handle multiple async callbacks in parallel

A

Use libraries like async.js or
Promise.all()
to manage execution flow.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What is a simple callback hell example

A

setTimeout(() => { console.log(‘1’); setTimeout(() => { console.log(‘2’) } ,1000) } ,1000).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What is a Promise in JavaScript

A

A promise is an object representing the eventual completion or failure of an asynchronous operation along with its resulting value

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

Why are Promises used

A

Promises solve the issue of callback hell and make asynchronous code more readable and manageable

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What are the three states of a Promise

A

Pending Fulfilled and Rejected

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
What does the Pending state signify
Pending means the promise is neither fulfilled nor rejected yet
26
What does the Fulfilled state signify
Fulfilled means the operation was completed successfully and the promise has a value
27
What does the Rejected state signify
Rejected means the operation failed and the promise has an error or reason
28
What happens once a promise is fulfilled or rejected
The promise becomes settled and cannot change states
29
How is a promise created
A promise is created using the Promise constructor with an executor function having resolve and reject parameters
30
What does the resolve function do
Resolve marks the promise as fulfilled and provides its value
31
What does the reject function do
Reject marks the promise as rejected and provides a reason or error
32
What is chaining in Promises
Chaining is a way to handle sequences of asynchronous operations using then catch and finally
33
What is the purpose of the then method
The then method handles the value of a fulfilled promise
34
What is the purpose of the catch method
The catch method handles errors when a promise is rejected
35
What is the purpose of the finally method
The finally method runs code after a promise is settled regardless of its outcome
36
How can Promises avoid callback hell
Promises allow structured chaining instead of deeply nested callbacks
37
What happens if there is an error in a promise chain
The error propagates to the catch block in the chain
38
What is an example of a real-world promise
Fetching data from an API where the promise resolves with the data or rejects with an error
39
What are the benefits of Promises
Promises provide better readability error handling and avoid callback hell
40
How are Promises different from Callbacks
Promises provide structured chaining and centralized error handling unlike manual handling in callbacks
41
What is callback hell
Callback hell refers to deeply nested callbacks that make code harder to read and maintain
42
What method is used to handle both success and failure cases of a Promise
The finally method handles both cases and runs regardless of success or failure
43
Question
Code
44
What is a promise
// A Promise represents an asynchronous operation const promise = new Promise((resolve, reject) => { const success = true; if (success) { resolve("Operation successful!"); } else { reject("Operation failed!"); } });
45
Why use promises in JavaScript
// Promises solve callback hell by allowing cleaner asynchronous handling fetchData() .then(result => console.log(result)) .catch(error => console.error(error));
46
What are the three states of a promise
// A promise has three states: pending, fulfilled, and rejected const promise = new Promise((resolve, reject) => { setTimeout(() => resolve("Success"), 1000); });
47
How is a promise created in JavaScript
// Creating a promise with the Promise constructor const promise = new Promise((resolve, reject) => { const operationSuccess = true; if (operationSuccess) resolve("Done!"); else reject("Error!"); });
48
What does resolve do in a promise
// resolve marks a promise as fulfilled const promise = new Promise((resolve) => resolve("Fulfilled!"));
49
What does reject do in a promise
// reject marks a promise as rejected const promise = new Promise((_, reject) => reject("Rejected!"));
50
How does chaining work with then and catch
// Chaining with .then() and .catch() fetchData() .then(data => processStep1(data)) .then(data => processStep2(data)) .catch(err => console.error(err));
51
What is the purpose of finally in promises
// finally() runs regardless of the promise's outcome const promise = new Promise((resolve) => resolve("Done")); promise .then(result => console.log(result)) .finally(() => console.log("Operation complete"));
52
How to handle errors in promises using catch
// Handling errors with .catch() const promise = new Promise((_, reject) => reject("Error occurred")); promise.catch(error => console.error(error));
53
How does promise chaining work with multiple steps
// Chaining multiple promises step1() .then(data => step2(data)) .then(result => step3(result)) .catch(error => console.error(error));
54
What are the advantages of promises over callbacks
// Advantages: Readable code, avoids callback hell ` const promise = new Promise((resolve, reject) => { const success = true; success ? resolve("Success") : reject("Failure"); }); promise .then(result => console.log(result)) .catch(err => console.error(err)); `
55
56
async/await in JavaScript
"Async/await is a modern syntax used to handle asynchronous operations. It is built on top of Promises and provides a cleaner more readable approach to asynchronous programming."
57
What is the `async` keyword?
"The `async` keyword is used to define an asynchronous function. It always returns a Promise which resolves to the return value of the function."
58
What is the `await` keyword?
"The `await` keyword is used to pause the execution of an `async` function until the Promise it is waiting for settles. It can only be used inside an `async` function."
59
Why use async/await?
"Async/await improves readability error handling and helps avoid callback hell making asynchronous code more manageable and easier to understand."
60
How does async/await work?
"When an `async` function is called it returns a Promise. The `await` keyword pauses the execution until the Promise is resolved or rejected."
61
Can you chain async functions?
"Yes async functions can be chained sequentially using `await` to ensure that each task runs after the previous one completes."
62
How does error handling work with async/await?
"Errors in async functions can be handled using `try...catch` blocks which simplify error handling compared to using `.catch()` with Promises."
63
What is the role of `Promise.all` with async/await?
"To execute multiple asynchronous operations in parallel you can use `Promise.all` to wait for multiple Promises to resolve simultaneously."
64
What is the basic syntax of an async function?
"The basic syntax is `async function functionName() { // asynchronous operations }`."
65
How do you use `await` in async functions?
"You use `await` to pause execution until a Promise resolves. For example `const result = await promise;`."
66
What happens when an async function returns a value?
"An async function always returns a Promise. If it returns a value that value is wrapped in a resolved Promise."
67
Can async/await be used to handle sequential execution?
"Yes async/await allows you to write sequential code by waiting for one Promise to resolve before moving to the next."
68
What are some limitations of async/await?
"Async/await can lead to unnecessary sequential execution if not used efficiently. It also requires transpilation for compatibility with older browsers."
69
How does async/await compare to Promises?
"Async/await is a more readable and synchronous-like approach to working with Promises. It eliminates `.then()` chaining and allows better error handling."
70
What is the role of `try...catch` in async/await?
"`try...catch` blocks are used to handle errors in async functions allowing centralized error handling."
71
What are the best practices for using async/await?
"Always use `try...catch` for error handling avoid unnecessary sequential execution and use `Promise.all` for parallel tasks."
72
How can async/await improve readability?
"Async/await makes asynchronous code more readable by removing nested `.then()` chains making it look more like synchronous code."
73
What are the advantages of async/await?
"Async/await simplifies asynchronous code improves error handling with `try...catch` and avoids callback hell making code more maintainable."
74
How do you handle errors in async/await?
"You handle errors by using `try...catch` inside the async function. If a Promise is rejected the error can be caught in the `catch` block."
75
Can async/await be used for API calls?
"Yes async/await is ideal for handling API calls where you can wait for responses before proceeding with the next operation."
76
What are the limitations of async/await?
"Async/await can lead to sequential execution where parallel execution would be more efficient. It's also not supported in older browsers without transpilation."
77
What is a real-world use case for async/await?
"Async/await is useful for managing sequential asynchronous tasks such as fetching data from APIs or processing files one step at a time."
78
What are some best practices for async/await?
"Always handle errors with `try...catch` use `Promise.all` for parallel tasks and ensure compatibility with older browsers using tools like Babel."