Asynchronous Promises
A Promise represents the future result of an asynchronous operation.
"I Promise a Result!"
A Promise represents the future result of an asynchronous operation.
It acts as a placeholder for a value that is not available yet.
When the operation finishes, the Promise is either fulfilled with a value or rejected with an error.
Why Promises?
Callbacks work well for simple asynchronous operations.
However, several dependent callbacks can become difficult to read.
Promises provide a cleaner and more readable way to organize asynchronous code.
Callback Example
Example Code
javascriptstep1(function(result1) {
step2(result1, function(result2) {
step3(result2, function(result3) {
display(result3);
});
});
});The Same Flow with Promises
Example Code
javascriptstep1()
.then(step2)
.then(step3)
.then(display);The code becomes flatter and easier to read.
Promise States
Every Promise is always in one of three states.
| State | Description |
|---|---|
| Pending | The operation has started but has not finished. |
| Fulfilled | The operation completed successfully. |
| Rejected | The operation failed. |
Pending │ ├────────► Fulfilled │ └────────► Rejected > A Promise is settled when it is fulfilled or rejected. --- ## Promises Returned by JavaScript APIs Many JavaScript APIs return Promises.
The fetch() method is one example.
Example
Example Code
javascriptfetch("fetch.txt")
.then(function(response) {
return response.text();
})
.then(function(text) {
myDisplayer(text);
})
.catch(function(error) {
myDisplayer(error);
});The fetch() method immediately returns a Promise.
The download continues in the background while JavaScript runs other code.
How then() Works
The then() method is called immediately.
It registers a function that JavaScript will call after the Promise is fulfilled.
The registered function runs later when the Promise has a result.
Each call to then() returns a new Promise.
Promise Flow
fetch() ⮯ returns a Promise ⮯ then() registers a callback ⮯ JavaScript continues ⮯ Promise becomes fulfilled ⮯ callback runs ### Example ``javascript let promise = fetch("fetch.txt"); promise.then(function(response) { return response.text(); }); myDisplayer("JavaScript continues..."); ` > The callback passed to then() receives the Promise's fulfillment value. > For fetch(), that value is a Response object. > In the next section you will learn how to create your own Promise. --- --- ## Creating a Promise Most of the time you will use Promises returned by JavaScript APIs such as fetch()`.
Sometimes you need to create your own Promise.
Create a Promise with the Promise() constructor.
Syntax
Example Code
javascriptconst promise = new Promise(function(resolve, reject) {
// Asynchronous work
if (success) {
resolve(value);
} else {
reject(error);
}
});The constructor receives a function with two parameters.
| Parameter | Description |
|---|---|
resolve | Fulfills the Promise with a value. |
reject | Rejects the Promise with an error. |
Example
Create and Use a Promise
Example Code
javascriptconst promise = new Promise(function(resolve, reject) {
const success = true;
if (success) {
resolve("Operation completed");
} else {
reject("Operation failed");
}
});
promise.then(function(value) {
myDisplayer(value);
})
.catch(function(error) {
myDisplayer(error);
});The then() Method
The then() method registers a function that handles a fulfilled Promise.
The registered function receives the fulfillment value.
Example
Example Code
javascriptfetch("fetch.txt")
.then(function(response) {
return response.text();
})
.then(function(text) {
myDisplayer(text);
});The catch() Method
The catch() method registers a function that handles a rejected Promise.
Example
Example Code
javascriptfetch("missing.txt")
.then(function(response) {
if (!response.ok) {
throw new Error(response.statusText);
}
return response.text();
})
.then(function(text) {
myDisplayer(text);
})
.catch(function(error) {
myDisplayer(error.message);
});The finally() Method
The finally() method registers a function that runs when a Promise settles.
It runs whether the Promise is fulfilled or rejected.
Example
Example Code
javascriptfetch("fetch.txt")
.then(function(response) {
return response.text();
})
.then(function(text) {
myDisplayer(text);
})
.catch(function(error) {
myDisplayer(error.message);
})
.finally(function() {
myDisplayer("Finished");
});Promise Chaining
Since then() returns a new Promise, several asynchronous operations can be chained together.
Example
Example Code
javascriptfunction step1() {
return Promise.resolve("A");
}
function step2(value) {
return Promise.resolve(value + "B");
}
function step3(value) {
return Promise.resolve(value + "C");
}
step1()
.then(function(value) {
return step2(value);
})
.then(function(value) {
return step3(value);
})
.then(function(value) {
myDisplayer(value);
})
.catch(function(error) {
myDisplayer(error);
});Returning a Promise
If a then() callback starts another asynchronous operation, return its Promise.
Correct
Example Code
javascriptstep1()
.then(function(value) {
return step2(value);
})
.then(function(value) {
myDisplayer(value);
});If you forget to return the Promise, the next step in the chain may run before the asynchronous operation has finished.
Common Promise Mistakes
Forgetting to Return a Promise
If a then() callback starts another asynchronous operation, return its Promise.
Incorrect
Example Code
javascriptstep1()
.then(function(value) {
step2(value);
})
.then(function(value) {
myDisplayer(value);
});The second then() may run before step2() has finished.
Correct
Example Code
javascriptstep1()
.then(function(value) {
return step2(value);
})
.then(function(value) {
myDisplayer(value);
});Forgetting to Handle Errors
Unhandled Promise rejections make debugging difficult.
Use catch() to handle errors.
Example
Example Code
javascriptfetch("missing.txt")
.then(function(response) {
if (!response.ok) {
throw new Error(response.statusText);
}
return response.text();
})
.catch(function(error) {
myDisplayer(error.message);
});Expecting Promises to Block JavaScript
Creating a Promise does not pause JavaScript.
JavaScript continues executing while the asynchronous operation is in progress.
Example
Example Code
javascriptmyDisplayer("Start");
fetch("fetch.txt")
.then(function() {
myDisplayer("Finished");
});
myDisplayer("JavaScript continues");The output is:
Start JavaScript continues Finished
Promises and Asynchronous Programming
A Promise represents the result of an asynchronous operation.
The asynchronous work is usually performed by a browser API such as fetch() or setTimeout().
The Promise provides a clean way to receive the result when that operation finishes.
Promises and the Event Loop
Promise callbacks do not run immediately.
They are scheduled to run after the current JavaScript task has completed.
The JavaScript Event Loop is responsible for running these callbacks.
Promises vs Callbacks
| Callbacks | Promises |
|---|---|
| Can become deeply nested. | Can be chained. |
| Error handling is often spread throughout the code. | A single catch() can handle errors from the entire chain. |
| Harder to read for complex operations. | More readable for multiple asynchronous steps. |
Summary
- A Promise represents the future result of an asynchronous operation.
- A Promise is either pending, fulfilled, or rejected.
- then() registers fulfillment handlers.
- catch() registers rejection handlers.
- finally() registers a handler that runs when the Promise settles.
- Return Promises from then() to keep Promise chains in the correct order.
- Most JavaScript APIs, including fetch(), return Promises.
Interactive Code Examples
Callback Example
javascriptstep1(function(result1) {
step2(result1, function(result2) {
step3(result2, function(result3) {
display(result3);
});
});
});The Same Flow with Promises
javascriptstep1()
.then(step2)
.then(step3)
.then(display);JS Example 3
javascriptfetch("fetch.txt")
.then(function(response) {
return response.text();
})
.then(function(text) {
myDisplayer(text);
})
.catch(function(error) {
myDisplayer(error);
});JS Example 4
javascriptlet promise = fetch("fetch.txt");
promise.then(function(response) {
return response.text();
});
myDisplayer("JavaScript continues...");Syntax
javascriptconst promise = new Promise(function(resolve, reject) {
// Asynchronous work
if (success) {
resolve(value);
} else {
reject(error);
}
});Create and Use a Promise
javascriptconst promise = new Promise(function(resolve, reject) {
const success = true;
if (success) {
resolve("Operation completed");
} else {
reject("Operation failed");
}
});
promise.then(function(value) {
myDisplayer(value);
})
.catch(function(error) {
myDisplayer(error);
});