Bird
Raised Fist0
Javascriptprogramming~10 mins

Why promises are used in Javascript - Visual Breakdown

Choose your learning style10 modes available
Concept Flow - Why promises are used
Start async task
↓
Create Promise
↓
Task runs in background
↓
Promise pending
↓
Resolve
↓
Then
↓
Continue with result or error handling
↓
End
This flow shows how a Promise starts an async task, waits for it to finish, then either resolves or rejects, allowing code to handle success or error.
Execution Sample
Javascript
const promise = new Promise((resolve, reject) => {
  setTimeout(() => resolve('Done'), 1000);
});
promise.then(result => console.log(result));
This code creates a Promise that waits 1 second, then resolves with 'Done', which is logged.
Execution Table
StepActionPromise StateCallback CalledOutput
1Create PromisePendingNo
2Start timer (1s)PendingNo
3Timer ends, call resolve('Done')FulfilledNo
4Then callback runs with 'Done'FulfilledYesLogs: Done
5End of executionFulfilledYesDone logged
💡 Promise resolved and then callback executed, so execution ends.
Variable Tracker
VariableStartAfter Step 1After Step 3After Step 4Final
promiseundefinedPending Promise objectFulfilled Promise objectFulfilled Promise objectFulfilled Promise object
Key Moments - 3 Insights
Why doesn't the code wait for the Promise to finish before moving on?
Because the Promise runs asynchronously (see Step 2 in execution_table), so JavaScript continues running other code while waiting.
What happens if the Promise is rejected instead of resolved?
The 'catch' callback would run instead of 'then' (not shown here), handling the error after rejection.
Why use Promises instead of just callbacks?
Promises make it easier to write and read async code by chaining actions and handling errors clearly (see Steps 3 and 4).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the Promise state at Step 2?
ARejected
BPending
CResolved
DSettled
💡 Hint
Check the 'Promise State' column at Step 2 in the execution_table.
At which step does the 'then' callback get called?
AStep 4
BStep 1
CStep 3
DStep 5
💡 Hint
Look at the 'Callback Called' column to find when it changes to 'Yes'.
If the Promise was rejected, which part of the code would run instead of 'then'?
ANo callback runs
B'then' callback
C'catch' callback
DBoth 'then' and 'catch' run
💡 Hint
Refer to key_moments about error handling and rejection.
Concept Snapshot
Promises handle async tasks by representing future results.
They start pending, then resolve or reject.
Use .then() for success, .catch() for errors.
They help avoid callback nesting and improve code clarity.
Full Transcript
Promises in JavaScript are used to manage asynchronous tasks. When a Promise is created, it starts in a pending state while the task runs in the background. Once the task finishes successfully, the Promise resolves, triggering the .then() callback to handle the result. If the task fails, the Promise rejects, triggering the .catch() callback for error handling. This allows JavaScript to continue running other code without waiting, making async code easier to write and read.

Practice

(1/5)
1. Why are promises used in JavaScript?
Promise helps with:
easy
A. Storing data permanently
B. Making the program run slower
C. Writing code without any functions
D. Handling tasks that take time without stopping the program

Solution

  1. Step 1: Understand what promises do

    Promises allow JavaScript to handle tasks like loading data without freezing the program.
  2. Step 2: Identify the correct purpose

    Promises help manage asynchronous tasks so the program keeps running smoothly.
  3. Final Answer:

    Handling tasks that take time without stopping the program -> Option D
  4. Quick Check:

    Promises = handle async tasks without blocking [OK]
Hint: Promises handle slow tasks without freezing code [OK]
Common Mistakes:
  • Thinking promises slow down the program
  • Confusing promises with data storage
  • Believing promises remove the need for functions
2. Which of the following is the correct way to create a promise in JavaScript?
easy
A. let p = new Promise((resolve, reject) => { /* code */ });
B. let p = Promise.create(() => { /* code */ });
C. let p = promise(() => { /* code */ });
D. let p = new promise { /* code */ };

Solution

  1. Step 1: Recall correct Promise syntax

    Promises are created with new Promise and a function with resolve and reject parameters.
  2. Step 2: Check each option

    Only let p = new Promise((resolve, reject) => { /* code */ }); uses the correct syntax with new Promise and arrow function.
  3. Final Answer:

    let p = new Promise((resolve, reject) => { /* code */ }); -> Option A
  4. Quick Check:

    Correct Promise syntax = new Promise(...) [OK]
Hint: Use 'new Promise' with resolve and reject functions [OK]
Common Mistakes:
  • Using lowercase 'promise' instead of 'Promise'
  • Trying to call Promise.create which doesn't exist
  • Missing parentheses or arrow function syntax
3. What will be the output of this code?
const p = new Promise((resolve) => {
  setTimeout(() => resolve('Done'), 100);
});
p.then(result => console.log(result));
console.log('Start');
medium
A. Start
Done
B. Done
Start
C. Done
Done
D. Start
Start

Solution

  1. Step 1: Understand asynchronous behavior

    The setTimeout delays the resolve call by 100ms, so console.log('Start') runs first.
  2. Step 2: Trace the output order

    First, 'Start' prints immediately, then after 100ms, 'Done' prints from the promise.
  3. Final Answer:

    Start
    Done
    -> Option A
  4. Quick Check:

    Async delay means 'Start' before 'Done' [OK]
Hint: setTimeout delays promise resolution, so logs appear after immediate code [OK]
Common Mistakes:
  • Assuming promise resolves immediately
  • Thinking 'Done' prints before 'Start'
  • Ignoring asynchronous nature of setTimeout
4. Find the error in this promise code:
const p = new Promise((resolve, reject) => {
  resolve('Success');
  reject('Error');
});
p.then(result => console.log(result))
 .catch(error => console.log(error));
medium
A. Promise must call reject first
B. Calling reject after resolve has no effect
C. Missing semicolon after resolve
D. Then and catch cannot be chained

Solution

  1. Step 1: Understand promise state changes

    Once a promise is resolved or rejected, its state is final and cannot change.
  2. Step 2: Analyze the code flow

    The promise calls resolve('Success') first, so the later reject('Error') is ignored.
  3. Final Answer:

    Calling reject after resolve has no effect -> Option B
  4. Quick Check:

    Promise settles once; later calls ignored [OK]
Hint: Promise settles once; later resolve/reject calls ignored [OK]
Common Mistakes:
  • Thinking reject overrides resolve if called later
  • Believing then and catch can't be chained
  • Confusing semicolon placement with logic errors
5. You want to fetch user data and then fetch posts for that user. Which approach best uses promises to handle this sequence?
hard
A. Use setTimeout to delay fetchPosts() after fetchUser()
B. Call fetchUser() and fetchPosts() separately without waiting
C. Call fetchUser(), then inside its .then(), call fetchPosts() and return that promise
D. Call fetchPosts() first, then fetchUser() inside its .then()

Solution

  1. Step 1: Understand promise chaining for dependent tasks

    When one task depends on another, use .then() to wait for the first before starting the second.
  2. Step 2: Identify correct chaining

    Call fetchUser(), then inside its .then(), call fetchPosts() and return that promise correctly calls fetchUser(), then in its .then(), calls fetchPosts() and returns its promise to chain properly.
  3. Final Answer:

    Call fetchUser(), then inside its .then(), call fetchPosts() and return that promise -> Option C
  4. Quick Check:

    Promise chaining = dependent tasks in sequence [OK]
Hint: Chain promises with then() for dependent async tasks [OK]
Common Mistakes:
  • Running dependent tasks in parallel without waiting
  • Using setTimeout instead of promise chaining
  • Calling tasks in wrong order
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard