- -- operator
- -= operator
- ++ operator
- += operator
- Accessing and setting content
- Array length
- Arrays
- Between braces
- Booleans
- Braces
- Callback function
- Calling the function
- Class
- Closure
- Code block
- Conditions
- Console
- Constructor
- Creating a p element
- Data types
- Destructuring
- Else
- Else if
- Equals operator
- Error Handling
- ES6
- Event loop
- Events
- Extend
- Fetch API
- Filter
- For loop
- Function
- Function name
- Greater than
- Head element
- Hoisting
- If statement
- JSON
- Less than
- Local storage
- Map
- Methods
- Module
- Numbers
- Overriding methods
- Parameters
- Promises
- Reduce
- Regular expressions
- Removing an element
- Replace
- Scope
- Session storage
- Sort
- Splice
- String
- Substring
- Template literals
- Tile
- Type conversion
- While loop
JAVASCRIPT
JavaScript Promises: Syntax, Usage, and Examples
JavaScript promises handle asynchronous operations, making it easier to work with APIs, databases, and other tasks that take time to complete. A promise represents a value that may be available now, in the future, or never. Instead of using callback functions, promises provide a cleaner and more manageable way to handle asynchronous operations.
How to Use JavaScript Promises
A JavaScript promise has three states:
- Pending – The operation is still in progress.
- Fulfilled – The operation completed successfully.
- Rejected – The operation failed.
Creating a Promise
You can create a promise using the Promise
constructor:
const myPromise = new Promise((resolve, reject) => {
let success = true;
if (success) {
resolve("Operation successful!");
} else {
reject("Something went wrong.");
}
});
This promise either resolves successfully or rejects based on a condition.
Handling Resolved and Rejected Promises
Once a promise is created, you can handle its result using .then()
and .catch()
:
myPromise
.then((result) => {
console.log(result); // "Operation successful!"
})
.catch((error) => {
console.error(error); // If rejected, this runs
});
JavaScript Promises then()
Method
The .then()
method runs when a promise is resolved. You can chain multiple .then()
calls to perform sequential operations:
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.error(error));
When to Use JavaScript Promises
Promises simplify working with asynchronous operations. Here are some common use cases:
- Fetching data from an API – Promises handle API requests that take time to return data.
- Reading files – If a script needs to read a file, promises ensure that the next operation waits for the file to load.
- Waiting for multiple operations – When multiple asynchronous functions need to complete before continuing, promises help structure the code.
- Chaining dependent operations – Promises allow sequential execution of functions that depend on previous results.
- Handling animations or timed events – Promises make it easier to delay or trigger animations at the right moment.
Examples of JavaScript Promises
Fetching Data from an API
fetch("https://jsonplaceholder.typicode.com/users/1")
.then((response) => response.json())
.then((user) => console.log(user.name))
.catch((error) => console.error("Error fetching user:", error));
Resolving a Promise After a Delay
function delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
delay(2000).then(() => console.log("Executed after 2 seconds"));
JavaScript Chain Promises
You can chain multiple .then()
calls when one promise depends on another:
function fetchUser() {
return fetch("https://jsonplaceholder.typicode.com/users/1").then((response) =>
response.json()
);
}
function fetchPosts(userId) {
return fetch(`https://jsonplaceholder.typicode.com/posts?userId=${userId}`).then(
(response) => response.json()
);
}
fetchUser()
.then((user) => fetchPosts(user.id))
.then((posts) => console.log("User posts:", posts))
.catch((error) => console.error("Error:", error));
Learn More About JavaScript Promises
Are JavaScript Promises Asynchronous?
Yes, promises run asynchronously, meaning JavaScript continues executing other code while waiting for a promise to resolve.
console.log("Start");
setTimeout(() => console.log("Timeout callback"), 0);
Promise.resolve().then(() => console.log("Promise resolved"));
console.log("End");
This outputs:
Start
End
Promise resolved
Timeout callback
Promises execute before setTimeout
callbacks but after synchronous code.
Async/Await and Promises in JavaScript
The async
and await
keywords make working with promises easier by allowing you to write asynchronous code that looks synchronous.
async function fetchData() {
try {
let response = await fetch("https://jsonplaceholder.typicode.com/todos/1");
let data = await response.json();
console.log(data);
} catch (error) {
console.error("Error fetching data:", error);
}
}
fetchData();
Instead of chaining .then()
, await
pauses execution until the promise resolves.
Await Multiple Promises in JavaScript
If you need to wait for multiple promises, use Promise.all()
.
const promise1 = fetch("https://jsonplaceholder.typicode.com/users/1").then((res) => res.json());
const promise2 = fetch("https://jsonplaceholder.typicode.com/posts/1").then((res) => res.json());
Promise.all([promise1, promise2])
.then((values) => console.log("User and post:", values))
.catch((error) => console.error("Error fetching data:", error));
This waits for both promises to resolve before executing the .then()
block.
Concurrent Promises in JavaScript
If you want the first resolved promise to return immediately, use Promise.race()
.
const slow = new Promise((resolve) => setTimeout(() => resolve("Slow"), 3000));
const fast = new Promise((resolve) => setTimeout(() => resolve("Fast"), 1000));
Promise.race([slow, fast]).then((winner) => console.log("Winner:", winner));
Since fast
resolves first, it prints "Winner: Fast"
.
Array of Promises in JavaScript
If you have an array of promises and want to execute them one after another, use reduce()
.
const urls = [
"https://jsonplaceholder.typicode.com/posts/1",
"https://jsonplaceholder.typicode.com/posts/2",
"https://jsonplaceholder.typicode.com/posts/3",
];
urls
.reduce(
(chain, url) => chain.then(() => fetch(url).then((res) => res.json()).then(console.log)),
Promise.resolve()
)
.catch(console.error);
Each request starts only after the previous one finishes.
JavaScript promises help manage asynchronous operations efficiently. They allow you to write cleaner, more structured code when dealing with API requests, file operations, and event-based programming.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.