codex-lv2-may-2025

πŸ“š Promise Reference Guide

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

Arrow functions are a concise way to write JavaScript functions. They’re especially useful in promise chains.

Basic Syntax

// Traditional function
function add(a, b) {
    return a + b;
}

// Arrow function equivalent
const add = (a, b) => a + b;

In Promise Chains

// 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

⏭️ The then Method

The then method is used to handle successful promise resolutions. It takes a callback function that receives the resolved value.

Why We Need then

Network 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:

Basic Usage

fetch('https://api.example.com/data')
    .then((response) => response.json())
    .then((data) => console.log(data))
    .catch((error) => console.error(error));

Key Points

Common Patterns

// 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);
});