Tags: #reference #javascript #promises #arrow-functions
Purpose: Quick reference for understanding arrow functions and the then method in JavaScript promises
Promises are JavaScript objects that represent the eventual completion (or failure) of an asynchronous operation, like an API call. The then method is a way to specify what should happen when a promise successfully completes - itβs like saying βwhen this finishes, do that.β Together, promises and then allow your code to wait for slow operations (like network requests) without freezing the entire webpage.
Arrow functions are a concise way to write JavaScript functions. Theyβre especially useful in promise chains.
// Traditional function
function add(a, b) {
return a + b;
}
// Arrow function equivalent
const add = (a, b) => a + b;
// Traditional function in .then()
.then(function(result) {
console.log(result);
return result.data;
})
// Arrow function equivalent
.then((result) => {
console.log(result);
return result.data;
})
| π‘ Learn more: W3Schools Arrow Functions | W3Schools JavaScript Promises |
then MethodThe then method is used to handle successful promise resolutions. It takes a callback function that receives the resolved value.
thenNetwork latency means API calls take time to complete. Without then, your code would try to use the data before it arrives, causing errors.
// β WRONG - This won't work!
const response = fetch('https://api.example.com/data');
console.log(response.data); // Error: data doesn't exist yet!
// β
CORRECT - Wait for the data to arrive
fetch('https://api.example.com/data')
.then((response) => {
// This code only runs AFTER the API call completes
console.log(response.data); // Now the data exists!
});
Think of it like ordering food:
.then() callback runs)fetch('https://api.example.com/data')
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.error(error));
.then() in chain// Single .then()
.then((result) => console.log(result))
// Chained .then() calls
.then((response) => response.json())
.then((data) => processData(data))
.then((processed) => displayResult(processed))
// With error handling
.then((result) => {
// Handle success
return result;
})
.catch((error) => {
// Handle errors
console.error(error);
});