JavaScript and TypeScript course Β· Module 4: Asynchronous JavaScript
Chaining Promises (then, catch, finally)
In this lesson12
In the previous exercise we learned the basics of creating and using Promise objects. Now let's dive deeper into techniques for chaining promises to build more complex asynchronous flows. In a system as complex as Jurassic Park, we often need to execute sequences of asynchronous operations, handle errors, and ensure systems work correctly.
Recap of Promise Methods
Before moving on to advanced techniques, let's recall the basic methods of the Promise object:
then(onFulfilled, onRejected)- registers handlers for fulfilled and rejected statescatch(onRejected)- registers a handler only for the rejected state (shorthand for.then(null, onRejected))finally(onFinally)- registers a handler that runs regardless of outcome
Each of these methods returns a new Promise, which is the foundation for chaining.
How Chaining Works
When you call .then() on a Promise, the return value of the callback determines the state of the new Promise:
Promise.resolve("start")
.then(value => {
console.log(value); // "start"
return "second step"; // plain value β next Promise resolves with it
})
.then(value => {
console.log(value); // "second step"
return Promise.resolve("third step"); // Promise β next Promise resolves with its value
})
.then(value => {
console.log(value); // "third step"
throw new Error("something went wrong"); // throw β next Promise rejects
})
.catch(error => {
console.error(error.message); // "something went wrong"
return "recovered"; // return in catch β chain continues
})
.then(value => {
console.log(value); // "recovered"
});Sequential Operations - Dinosaur Lab Pipeline
Let's build a full dinosaur creation pipeline in our Jurassic Park lab:
// Step functions - each returns a Promise
function collectDNASample(dinosaurId) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (dinosaurId > 0) {
resolve({ id: dinosaurId, dna: `ACGT-${dinosaurId}-TGCA`, quality: "high" });
} else {
reject(new Error("Invalid dinosaur ID for DNA collection"));
}
}, 800);
});
}
function sequenceDNA(sample) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (sample.quality === "high") {
resolve({ ...sample, sequence: `SEQ-${sample.dna}-END`, confidence: 0.98 });
} else {
reject(new Error(`DNA quality too low: ${sample.quality}`));
}
}, 1200);
});
}
function synthesizeProtein(sequencedDNA) {
return new Promise(resolve => {
setTimeout(() => {
resolve({
...sequencedDNA,
protein: `PROTEIN-${sequencedDNA.id}`,
aminoAcids: 847
});
}, 1000);
});
}
function createEmbryo(proteinData) {
return new Promise((resolve, reject) => {
setTimeout(() => {
const success = Math.random() > 0.2;
if (success) {
resolve({ embryoId: `EMB-${proteinData.id}`, viability: "high", source: proteinData });
} else {
reject(new Error("Embryo creation failed - insufficient protein"));
}
}, 1500);
});
}
// Full pipeline
console.log("=== Jurassic Park DNA Lab - Starting Pipeline ===");
collectDNASample(7)
.then(sample => {
console.log(`Step 1 - DNA collected: ${sample.dna} (quality: ${sample.quality})`);
return sequenceDNA(sample);
})
.then(sequenced => {
console.log(`Step 2 - DNA sequenced: ${sequenced.sequence} (confidence: ${sequenced.confidence})`);
return synthesizeProtein(sequenced);
})
.then(protein => {
console.log(`Step 3 - Protein synthesized: ${protein.protein} (${protein.aminoAcids} amino acids)`);
return createEmbryo(protein);
})
.then(embryo => {
console.log(`Step 4 - Embryo created: ${embryo.embryoId} (viability: ${embryo.viability})`);
console.log("Pipeline complete! Embryo ready for incubation.");
return embryo;
})
.catch(error => {
console.error(`Pipeline failed: ${error.message}`);
console.log("Initiating cleanup procedures...");
})
.finally(() => {
console.log("=== Lab Pipeline Finished ===");
});Return Values from then() and catch()
The value returned from a callback in .then() or .catch() becomes the value that the Promise returned by that method resolves with. This gives us the ability to transform data at every stage of the chain.
// Example of data transformation in a Promise chain
fetchDinosaurInfo(5)
.then(dinoData => {
// Transform dinosaur data into the format used by the UI
return {
id: dinoData.id,
name: dinoData.name || "Unknown",
display: `${dinoData.species} (${dinoData.age} lat)`,
dangerLevel: dinoData.carnivore ? "High" : "Low",
location: dinoData.enclosureId
};
})
.then(uiData => {
// Add additional UI information
return {
...uiData,
icon: uiData.dangerLevel === "High" ? "!!" : "OK",
description: `${uiData.icon} ${uiData.display} - Threat: ${uiData.dangerLevel}`
};
})
.then(finalData => {
console.log("Data for UI:", finalData);
updateDinoCard(finalData); // Update the user interface
});Error Handling in the Promise Chain
There are several strategies for handling errors in Promise chains:
1. Single catch at the end of the chain
prepareTransport(7) // Dinosaur with ID 7 is too large for standard transport
.then(transportInfo => loadDinosaur(transportInfo))
.then(shipmentInfo => transportToPark(shipmentInfo))
.then(deliveryInfo => placeInEnclosure(deliveryInfo))
.then(enclosureInfo => {
console.log("Success:", enclosureInfo);
})
.catch(error => {
// This catch handles errors from all previous steps
console.error("An error occurred:", error.message);
notifyAdministration(error);
});2. Multiple catches for different stages
prepareTransport(7)
.then(transportInfo => loadDinosaur(transportInfo))
.catch(error => {
// This catch handles errors only from prepareTransport and loadDinosaur
console.error("Error during preparation or loading:", error.message);
return orderOversizedTransport(7); // Alternative path - return a new Promise
})
.then(info => {
// This then receives either the result of loadDinosaur or orderOversizedTransport
return transportToPark(info);
})
.then(deliveryInfo => placeInEnclosure(deliveryInfo))
.catch(error => {
// This catch handles errors from transportToPark, placeInEnclosure or orderOversizedTransport
console.error("Error during transport or enclosure placement:", error.message);
notifySecurityTeam(error);
throw error; // Pass the error further
})
.catch(error => {
// This catch catches all unhandled errors
console.error("Critical error in the process:", error.message);
activateEmergencyProcedures();
});
function orderOversizedTransport(dinoId) {
console.log(`Ordering oversized transport for dinosaur #${dinoId}...`);
// Implementation returning a Promise
return Promise.resolve({
id: dinoId,
vehicle: "Reinforced special transport XL",
status: "Prepared"
});
}3. Error handling inside the then() function
prepareTransport(3)
.then(transportInfo => {
try {
// Code that may throw exceptions
validateTransport(transportInfo);
return loadDinosaur(transportInfo);
} catch (error) {
// Handling synchronous exceptions
console.error("Transport validation error:", error.message);
return repairTransport(transportInfo); // Return a new Promise
}
})
.then(shipmentInfo => transportToPark(shipmentInfo))
.catch(error => {
// Handling remaining errors
console.error("Process error:", error.message);
});
function validateTransport(transportInfo) {
if (!transportInfo.vehicle.includes("cage")) {
throw new Error("Transport does not have proper safety measures!");
}
}
function repairTransport(transportInfo) {
console.log("Repairing transport issues...");
return Promise.resolve({
...transportInfo,
vehicle: transportInfo.vehicle + " with a reinforced cage",
status: "Repaired"
});
}Error Transformation
The .catch() method can not only handle an error but also transform it into a success by returning a value:
fetchDinosaurInfo(999) // ID doesn't exist
.catch(error => {
console.log("Dinosaur not found:", error.message);
// Instead of propagating the error, return default data
return {
id: 999,
name: "Unknown",
species: "Unknown species",
age: "?",
carnivore: true,
enclosureId: "N/A"
};
})
.then(dinoData => {
// This then will execute with default data
console.log("Dinosaur data (default or actual):", dinoData);
updateUI(dinoData);
});Nested vs Chained - A Key Distinction
// NESTED (bad) - creates promise hell, error handling is messy
fetchDinosaurData(1).then(dino => {
fetchEnclosureData(dino.enclosureId).then(enclosure => {
fetchVetRecord(dino.id).then(record => {
// All three variables accessible here, but code is deeply nested
console.log(dino.name, enclosure.name, record.lastCheckup);
}).catch(e => console.error("vet error", e));
}).catch(e => console.error("enclosure error", e));
}).catch(e => console.error("dino error", e));
// CHAINED (good) - flat structure, single error handler
let dinoRef, enclosureRef;
fetchDinosaurData(1)
.then(dino => {
dinoRef = dino;
return fetchEnclosureData(dino.enclosureId);
})
.then(enclosure => {
enclosureRef = enclosure;
return fetchVetRecord(dinoRef.id);
})
.then(record => {
console.log(dinoRef.name, enclosureRef.name, record.lastCheckup);
})
.catch(error => {
// Catches any error from any step
console.error("Failed:", error.message);
});Conditional Chaining
Sometimes we want to conditionally skip steps:
function processEmergencyReport(reportId, urgency) {
return fetchReport(reportId)
.then(report => {
console.log(`Report received: ${report.title}`);
// Conditionally add extra step based on urgency
if (urgency === "critical") {
return notifyDirector(report).then(() => report); // Return report after notification
}
return report; // Skip notification for non-critical
})
.then(report => {
return logReport(report); // Always log
})
.then(() => {
console.log("Report processing complete.");
});
}
// Helper stubs
function fetchReport(id) { return Promise.resolve({ id, title: `Report #${id}`, data: {} }); }
function notifyDirector(r) { return new Promise(res => setTimeout(() => { console.log("Director notified"); res(); }, 300)); }
function logReport(r) { return new Promise(res => setTimeout(() => { console.log(`Logged: ${r.title}`); res(r); }, 200)); }
processEmergencyReport(42, "critical");
processEmergencyReport(43, "low");Using finally for Cleanup
finally is perfect for cleanup logic that must run regardless of success or failure:
function runLabExperiment(experimentId) {
let labResources = null;
return allocateLabResources(experimentId)
.then(resources => {
labResources = resources;
console.log(`Resources allocated: ${resources.resourceId}`);
return runExperiment(resources);
})
.then(result => {
console.log(`Experiment success: ${result.outcome}`);
return result;
})
.catch(error => {
console.error(`Experiment failed: ${error.message}`);
throw error; // Re-throw so caller knows it failed
})
.finally(() => {
// Always release resources, even if experiment failed
if (labResources) {
releaseLabResources(labResources);
console.log("Lab resources released.");
}
});
}
function allocateLabResources(id) {
return Promise.resolve({ resourceId: `LAB-RES-${id}`, equipment: ["centrifuge", "sequencer"] });
}
function runExperiment(resources) {
return new Promise((resolve, reject) => {
setTimeout(() => {
Math.random() > 0.3
? resolve({ outcome: "DNA extracted successfully" })
: reject(new Error("Experiment contamination detected"));
}, 1000);
});
}
function releaseLabResources(resources) {
console.log(`Releasing ${resources.resourceId}`);
}
runLabExperiment(101);Complex Operations with Promises
Sequential Execution of Asynchronous Operations on an Array
Sometimes we need to perform an asynchronous operation on each element of an array, one after another:
// Sequential dinosaur feeding
const dinosaurIds = [1, 2, 3, 4, 5];
// Function for feeding one dinosaur
function feedDinosaur(id) {
return new Promise((resolve, reject) => {
console.log(`Starting to feed dinosaur #${id}...`);
setTimeout(() => {
if (id === 3) {
reject(new Error(`Dinosaur #${id} refuses to eat!`));
return;
}
console.log(`Dinosaur #${id} fed!`);
resolve({id, status: 'fed', time: new Date().toISOString()});
}, 1000);
});
}
// Sequential feeding of all dinosaurs
dinosaurIds.reduce((promise, dinoId) => {
return promise
.then(results => {
// results is an array of results from previous operations
return feedDinosaur(dinoId)
.then(result => {
// Add the result to the results array
return [...results, result];
})
.catch(error => {
console.error(`Error feeding dinosaur #${dinoId}:`, error.message);
// Add error information to the results
return [...results, {id: dinoId, status: 'error', error: error.message}];
});
});
}, Promise.resolve([])) // Start with an empty results array
.then(allResults => {
console.log("All dinosaurs processed:");
console.log(allResults);
// Check if all dinosaurs have been fed
const allFed = allResults.every(result => result.status === 'fed');
if (allFed) {
console.log("All dinosaurs have been fed!");
} else {
console.log("Not all dinosaurs have been fed - check the report.");
}
});Executing Asynchronous Operations with a Limited Number of Parallel Tasks
// Function for executing async operations with limited parallelism
async function executeWithLimit(array, promiseFunction, parallelLimit) {
const allResults = [];
// Execute tasks in batches
for (let i = 0; i < array.length; i += parallelLimit) {
const batch = array.slice(i, i + parallelLimit);
// Run Promise.all for a batch of tasks
const results = await Promise.all(
batch.map(element =>
promiseFunction(element)
.catch(error => {
console.error(`Error for element ${element}:`, error.message);
return { element, status: 'error', error: error.message };
})
)
);
allResults.push(...results);
console.log(`Completed batch ${i / parallelLimit + 1} (${results.length} operations)`);
}
return allResults;
}
// Using the function for parallel but limited health checks on dinosaurs
const allDinosaurIds = Array.from({ length: 20 }, (_, i) => i + 1);
function checkDinosaurHealth(id) {
return new Promise((resolve, reject) => {
console.log(`Checking health of dinosaur #${id}...`);
setTimeout(() => {
// Simulate random health status
const health = Math.floor(Math.random() * 100);
if (health < 30) {
reject(new Error(`Dinosaur #${id} has health problems! Health level: ${health}`));
return;
}
console.log(`Dinosaur #${id} is healthy. Health level: ${health}`);
resolve({id, health, status: 'healthy'});
}, 500 + Math.random() * 1000); // Random execution time
});
}
// Check health of at most 5 dinosaurs at a time
executeWithLimit(allDinosaurIds, checkDinosaurHealth, 5)
.then(results => {
console.log("Health check of all dinosaurs completed:");
const healthy = results.filter(w => w.status === 'healthy').length;
const chore = results.filter(w => w.status === 'error').length;
console.log(`Healthy: ${healthy}, Requiring attention: ${chore}`);
// Display dinosaurs that need attention
if (sick > 0) {
console.log("Dinosaurs requiring veterinary intervention:");
results
.filter(w => w.status === 'error')
.forEach(w => console.log(`- Dinosaur #${w.element}: ${w.error}`));
}
});Best Practices for Chaining Promises
Always return a Promise from then() functions - this ensures proper chaining and result propagation:
.then(data => { // Bad - doesn't return a Promise, the chain will be broken processData(data); }) .then(data => { // Good - returns the processing result to the next then() return processData(data); })Use a single catch() for a group of related operations - this makes the code more readable:
fetchEnclosureData(5) .then(data => updateEnclosureStatus(data)) .then(status => notifyStaff(status)) .catch(error => { // One catch for the entire enclosure update operation handleEnclosureError(error); }); // New, unrelated operation with its own catch fetchGuestList() .then(visitors => updateVisitorCount(visitors)) .catch(error => { // Separate catch for visitor-related operations handleVisitorError(error); });Use finally() for cleanup code - regardless of success or failure:
openEnclosureGate(enclosureId) .then(() => moveDinosaur(dinoId, enclosureId)) .catch(error => { logError("Move error:", error); throw error; // Propagate the error further }) .finally(() => { // Always close the gate, regardless of the outcome closeEnclosureGate(enclosureId); });Avoid deeply nested Promise chains - break them down into smaller, named functions:
// Instead of one long chain: function moveDinosaurToNewEnclosure(dinoId, newEnclosureId) { return fetchDinosaurInfo(dinoId) .then(dino => { // Check current enclosure return fetchEnclosureData(dino.enclosureId) .then(oldEnclosure => { // Prepare new enclosure return fetchEnclosureData(newEnclosureId) .then(newEnclosure => { // Check compatibility // ... more nested thens... }); }); }); } // Better - break into smaller functions: function moveDinosaurToNewEnclosure(dinoId, newEnclosureId) { return fetchDinosaurInfoWithCurrentEnclosure(dinoId) .then(data => checkEnclosureCompatibility(data, newEnclosureId)) .then(data => executeTransfer(data)); } function fetchDinosaurInfoWithCurrentEnclosure(dinoId) { let dinoData; return fetchDinosaurInfo(dinoId) .then(dino => { dinoData = dino; return fetchEnclosureData(dino.enclosureId); }) .then(oldEnclosure => { return { dino: dinoData, oldEnclosure }; }); } function checkEnclosureCompatibility(data, newEnclosureId) { return fetchEnclosureData(newEnclosureId) .then(newEnclosure => { // Check compatibility return { ...data, newEnclosure }; }); } function executeTransfer(data) { // Transfer implementation return Promise.resolve({ status: "completed", ...data }); }
Summary
Chaining Promises with .then(), .catch(), and .finally() gives you powerful tools for building complex asynchronous flows. A well-designed Promise chain can make even complicated asynchronous operations, like managing dinosaur transport in Jurassic Park, readable and easy to maintain.
Key principles:
- Always return a Promise from functions in
.then()to continue the chain - Use
.catch()for unified error handling - Use
.finally()for cleanup operations - Avoid nesting Promises in favor of chaining
- Break complex operations into smaller, named functions
In the next exercise we will explore more advanced methods for working with multiple Promises simultaneously, such as Promise.all(), Promise.race(), and Promise.allSettled().
Code for this lesson: index.js
// Arrow Function Converter - Modern functions
console.log("ARROW FUNCTIONS IN JURASSIC PARK\n");
// Traditional function
function calculateFeedingCost(dinosaurCount, costPerDinosaur) {
return dinosaurCount * costPerDinosaur;
}
// Arrow function - shorter syntax
const calculateFeedingCostArrow = (dinosaurCount, costPerDinosaur) => {
return dinosaurCount * costPerDinosaur;
};
// Arrow function - implicit return (without {})
const calculateFeedingCostShort = (dinosaurCount, costPerDinosaur) =>
dinosaurCount * costPerDinosaur;
console.log("=== SYNTAX COMPARISON ===\n");
const trexCount = 3;
const costPerTRex = 5000;
console.log("Traditional function:");
console.log(`Cost: $${calculateFeedingCost(trexCount, costPerTRex)}`);
console.log("\nArrow function:");
console.log(`Cost: $${calculateFeedingCostArrow(trexCount, costPerTRex)}`);
console.log("\nArrow function (short):");
console.log(`Cost: $${calculateFeedingCostShort(trexCount, costPerTRex)}`);
// Arrow functions in array methods
console.log("\n=== ARROW FUNCTIONS WITH ARRAYS ===\n");
const dinosaurs = [
{ name: 'T-Rex', danger: 10 },
{ name: 'Velociraptor', danger: 8 },
{ name: 'Triceratops', danger: 3 },
{ name: 'Brachiosaurus', danger: 2 }
];
// Filter - only the dangerous ones
const dangerous = dinosaurs.filter(dino => dino.danger > 5);
console.log("Dangerous dinosaurs:");
dangerous.forEach(dino => console.log(` - ${dino.name} (danger: ${dino.danger}/10)`));
// Map - list of names
const names = dinosaurs.map(dino => dino.name);
console.log("\nAll species:", names.join(', '));
// Reduce - average danger level
const avgDanger = dinosaurs.reduce((sum, dino) => sum + dino.danger, 0) / dinosaurs.length;
console.log(`\nAverage danger: ${avgDanger.toFixed(1)}/10`);Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What does the .then() method do on a Promise?
2. What is the .catch() method used for in a Promise?
Hands-on tasks in the game
- Code editor
Rewrite callback hell into a Promise chain - connect three asynchronous operations using .then() and add error handling with .catch().
- Vertical ordering
Arrange the stages of growing callback nesting (callback hell):