Asynchronous JavaScript in LWC · Lesson 14 of 25
Promises in LWC: then, catch and Promise.all
A promise is an object that stands for a value you'll have later: the result of an Apex call, a record saved by updateRecord, a modal's result. Imperative Apex methods, uiRecordApi functions and LightningModal.open() all return promises, so this is everyday LWC code.
In this lesson
- The three states of a promise
- Chaining with then, catch and finally
- Creating your own promises
- Promise.all, allSettled, race and any
- Parallel Apex calls in a component
States and chaining
A promise's life
- pendingthe work is in progress
- fulfilledit succeeded – then() callbacks get the value
- rejectedit failed – catch() gets the error
- settledeither way – finally() runs (hide the spinner here)
// a stand-in for an imperative Apex call
const getAccount = (id) =>
new Promise((resolve, reject) => {
setTimeout(() => (id ? resolve({ Id: id, Name: 'Acme', Rating: 'Warm' }) : reject(new Error('Id is required'))), 20);
});
getAccount('001A')
.then((account) => account.Name) // return a value → next then gets it
.then((name) => console.log(`loaded ${name}`))
.catch((error) => console.log(`error: ${error.message}`))
.finally(() => console.log('spinner off'));
getAccount(null)
.then((account) => console.log('never runs', account))
.catch((error) => console.log(`error: ${error.message}`))
.finally(() => console.log('spinner off'));
loaded Acme spinner off error: Id is required spinner off
- Each
thenreturns a new promise, so steps chain flat instead of nesting. - Return a promise from a
thenand the chain waits for it – that's how you sequence dependent calls. - One
catchat the end handles a failure in any earlier step.
The forgotten return
.then((acc) => { getContacts(acc.Id); }) starts the call but doesn't return it, so the next then runs immediately with undefined and errors from getContacts are never caught. With braces, always return the promise.
Wrapping a callback API
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
function withTimeout(promise, ms) {
const timeout = new Promise((_, reject) => setTimeout(() => reject(new Error(`timed out after ${ms}ms`)), ms));
return Promise.race([promise, timeout]); // whichever settles first wins
}
const slowCall = delay(200).then(() => 'slow result');
const fastCall = delay(10).then(() => 'fast result');
withTimeout(fastCall, 100).then(console.log);
withTimeout(slowCall, 100).catch((e) => console.log(e.message));
fast result timed out after 100ms
Promise.all, allSettled and any
const ok = (value, ms) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
const fail = (msg, ms) => new Promise((_, reject) => setTimeout(() => reject(new Error(msg)), ms));
// all: everything must succeed; results in the same order as the input
Promise.all([ok('accounts', 30), ok('contacts', 10)])
.then((results) => console.log('all:', results));
// all fails fast on the first rejection
Promise.all([ok('accounts', 30), fail('contacts query failed', 10)])
.catch((e) => console.log('all rejected:', e.message));
// allSettled: wait for everything and report each outcome
Promise.allSettled([ok('accounts', 30), fail('contacts query failed', 10)])
.then((results) => console.log('allSettled:', results.map((r) => r.status)));
// any: the first success wins (useful for fallbacks)
Promise.any([fail('primary down', 5), ok('from backup', 20)])
.then((v) => console.log('any:', v));
all rejected: contacts query failed any: from backup all: [ 'accounts', 'contacts' ] allSettled: [ 'fulfilled', 'rejected' ]
| Method | Resolves when | Rejects when | LWC use |
|---|---|---|---|
Promise.all | all succeed | any one fails | load several things a screen needs |
Promise.allSettled | all finish | never | bulk updates where some may fail |
Promise.race | first to settle succeeds | first to settle fails | timeouts |
Promise.any | first success | all fail | fallback sources |
Parallel Apex calls in a component
When two calls don't depend on each other, start both and wait for both. The page loads in the time of the slowest call instead of the sum of both:
// accountOverview.js
import { LightningElement, api } from 'lwc';
import getOpenCases from '@salesforce/apex/OverviewController.getOpenCases';
import getOpenOpportunities from '@salesforce/apex/OverviewController.getOpenOpportunities';
export default class AccountOverview extends LightningElement {
@api recordId;
summary = 'Loading…';
connectedCallback() {
Promise.all([
getOpenCases({ accountId: this.recordId }),
getOpenOpportunities({ accountId: this.recordId }),
])
.then(([cases, opportunities]) => { // destructure the results array
const pipeline = opportunities.reduce((sum, o) => sum + o.Amount, 0);
this.summary = `${cases.length} open cases · ${opportunities.length} deals worth ${pipeline}`;
})
.catch((error) => {
this.summary = `Could not load overview: ${error.body?.message ?? error.message}`;
});
}
}
<!-- accountOverview.html -->
<template>
<p>{summary}</p>
</template>
2 open cases · 2 deals worth 75000
getOpenCases called 1× with {"accountId":"001A"}
getOpenOpportunities called 1× with {"accountId":"001A"}Apex errors arrive as an object with a body.message (for most server errors), not as a plain Error – hence error.body?.message ?? error.message. A reusable helper for this is in the error handling lesson.
Practice
Try it yourself
You update 20 records with
updateRecordand want to show "17 saved, 3 failed". Which Promise method fits?Show answer
Promise.allSettled(records.map((r) => updateRecord({ fields: r }))), then count results withstatus === 'fulfilled'and'rejected'.Promise.allwould stop at the first failure.What's wrong here?
getAccount(id).then((a) => { getContacts(a.Id); }).then((contacts) => this.contacts = contacts);Show answer
The first
thendoesn't returngetContacts(…), socontactsis undefined. Write.then((a) => getContacts({ accountId: a.Id })).
Quick check
What are the three states of a promise?
pending, fulfilled and rejected.
Does Promise.all return results in completion order?
No – in the order of the input array.
Where should you hide a loading spinner?
In finally(), so it runs on success and failure.
Summary
- Promises represent future values; chain with then, handle errors with catch, clean up in finally.
- Always return promises from then callbacks.
- Promise.all for parallel loads, allSettled for partial success, race for timeouts.
- Apex errors usually carry their message in error.body.message.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.