LearnFrenzy
Sign in Take a free test

Asynchronous JavaScript in LWC · Lesson 14 of 25

Promises in LWC: then, catch and Promise.all

5 min read Updated Nov 8, 2026 Saurabh Samir

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

  1. pendingthe work is in progress
  2. fulfilledit succeeded – then() callbacks get the value
  3. rejectedit failed – catch() gets the error
  4. 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'));

Output

loaded Acme
spinner off
error: Id is required
spinner off
  • Each then returns a new promise, so steps chain flat instead of nesting.
  • Return a promise from a then and the chain waits for it – that's how you sequence dependent calls.
  • One catch at 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));

Output

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

Output

all rejected: contacts query failed
any: from backup
all: [ 'accounts', 'contacts' ]
allSettled: [ 'fulfilled', 'rejected' ]
MethodResolves whenRejects whenLWC use
Promise.allall succeedany one failsload several things a screen needs
Promise.allSettledall finishneverbulk updates where some may fail
Promise.racefirst to settle succeedsfirst to settle failstimeouts
Promise.anyfirst successall failfallback 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>

Result

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

  1. You update 20 records with updateRecord and want to show "17 saved, 3 failed". Which Promise method fits?

    Show answer

    Promise.allSettled(records.map((r) => updateRecord({ fields: r }))), then count results with status === 'fulfilled' and 'rejected'. Promise.all would stop at the first failure.

  2. What's wrong here? getAccount(id).then((a) => { getContacts(a.Id); }).then((contacts) => this.contacts = contacts);

    Show answer

    The first then doesn't return getContacts(…), so contacts is 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.

Next lesson

Search LearnFrenzy

Esc

Quick links