Sub topic 5
Working with the returned Promise
This chapter assumes you can read basic JavaScript, including arrow functions and the async keyword. It also assumes you have already imported an Apex method and called it from an event handler. Here you learn what that call returns, how the result and errors reach your code, and how to combine several calls without introducing bugs.
What the call gives you
An imported Apex method is a JavaScript function. When you call it, it does not return the Apex result. It returns a Promise, which is an object that stands for a value that will exist later. The browser sends the request to the server, and your code keeps running while it waits.
A Promise is always in one of three states:
| State | Meaning | What you receive |
|---|---|---|
| Pending | The server has not answered yet | Nothing |
| Fulfilled | Apex returned normally | The return value of the Apex method |
| Rejected | Apex threw an exception, or the request failed | An error object |
A Promise leaves the pending state once. It cannot be fulfilled and then rejected afterward. Your code reacts to the final state with then/catch or with await.
Using then and catch
The then method takes a function that receives the fulfilled value. The catch method takes a function that receives the rejection. Both return a new Promise, so you can chain them.
import { LightningElement } from 'lwc';
import searchContacts from '@salesforce/apex/ContactController.searchContacts';
export default class ContactSearchThen extends LightningElement {
contacts = [];
errorMessage;
handleSearch() {
searchContacts({ searchTerm: 'Ada' })
.then((result) => {
this.contacts = result;
this.errorMessage = undefined;
})
.catch((error) => {
this.contacts = [];
this.errorMessage = error?.body?.message || 'Unknown error';
})
.finally(() => {
// Runs after either outcome. Use it for cleanup.
});
}
}Three details matter here:
- The handler returns nothing, so the caller cannot wait for the work to finish. If another piece of code needs to know when the search is done, return the Promise chain with
return searchContacts(...). catchalso catches exceptions thrown inside the earlierthencallback. A typo in thethenbody shows up as an "error from Apex" unless you check what you caught.finallyreceives no arguments and cannot see the result or error. It is for cleanup only.
Using async and await
await pauses the current function until the Promise settles. It then gives you the fulfilled value, or throws the rejection so a try/catch can handle it. A function that uses await must be marked async, and an async function always returns a Promise.
import { LightningElement } from 'lwc';
import searchContacts from '@salesforce/apex/ContactController.searchContacts';
export default class ContactSearchAwait extends LightningElement {
contacts = [];
errorMessage;
async handleSearch() {
try {
this.contacts = await searchContacts({ searchTerm: 'Ada' });
this.errorMessage = undefined;
} catch (error) {
this.contacts = [];
this.errorMessage = error?.body?.message || 'Unknown error';
}
}
}The two styles do the same work, so choose by readability. With await, steps that depend on each other read top to bottom, and one try/catch covers all of them. With then/catch, a simple single call stays compact. Pick one style per component and keep to it.
Running calls in sequence
Use sequential await when the second call needs the first call to finish. A common case is saving a change and then reloading the list. The updateEmail method from the controller returns void, so its Promise fulfills with undefined. You still must wait for it, because the server has not saved the change until the Promise fulfills.
async handleSave() {
try {
await updateEmail({ contactId: this.selectedId, email: this.newEmail });
this.contacts = await searchContacts({ searchTerm: this.searchTerm });
} catch (error) {
this.errorMessage = error?.body?.message || 'Unknown error';
}
}This assumes updateEmail is imported from @salesforce/apex/ContactController.updateEmail. If the first call rejects, execution jumps to catch and the second call never starts. That is the behavior you want here, because a failed save should not trigger a reload that hides the failure.
Running calls in parallel
If two calls do not depend on each other, do not await them one after the other. Each await waits for a full server round trip, so sequential awaits add the latencies together. Start both calls first, then wait for both with Promise.all.
async loadComparison() {
try {
const [groupA, groupB] = await Promise.all([
searchContacts({ searchTerm: 'A' }),
searchContacts({ searchTerm: 'B' })
]);
this.countA = groupA.length;
this.countB = groupB.length;
} catch (error) {
this.errorMessage = error?.body?.message || 'Unknown error';
}
}Promise.all returns an array of results in the same order as the input array, whatever order the responses arrive in. It rejects as soon as any one input rejects, and you only see that first error. The other calls still run to completion on the server, but their results are discarded.
When you need every outcome, including failures, use Promise.allSettled. It never rejects. It fulfills with an array of objects, each with status set to "fulfilled" or "rejected", and either a value or a reason.
const outcomes = await Promise.allSettled([
searchContacts({ searchTerm: 'A' }),
searchContacts({ searchTerm: 'B' })
]);
const failures = outcomes.filter((o) => o.status === 'rejected');Keep in mind that each Apex call is a separate server transaction. Parallel calls do not share a database transaction, so one cannot roll back another. If several changes must succeed or fail together, do them in a single Apex method.
Handling out-of-order responses
Responses do not always arrive in the order you sent the requests. If a user types quickly and each keystroke triggers a search, the answer for "Ad" can arrive after the answer for "Ada". The older answer then overwrites the newer one, and the screen shows results that do not match the input.
A simple fix is a request counter. Each call records its own number and checks it before writing state.
import { LightningElement } from 'lwc';
import searchContacts from '@salesforce/apex/ContactController.searchContacts';
export default class LatestWins extends LightningElement {
contacts = [];
latestRequest = 0;
async runSearch(term) {
const requestId = ++this.latestRequest;
try {
const result = await searchContacts({ searchTerm: term });
if (requestId !== this.latestRequest) {
return; // A newer request exists, so drop this answer.
}
this.contacts = result;
} catch (error) {
if (requestId === this.latestRequest) {
this.contacts = [];
}
}
}
}The check runs after the await, when the older request has already finished. This does not cancel the server work. It only stops stale data from reaching the UI. The chapter on avoiding unnecessary calls covers reducing the number of requests in the first place.
Common mistakes
- Forgetting
await.this.contacts = searchContacts(...)assigns a Promise to the property, and the template renders nothing useful. Check for this first when a list appears empty. - Using
awaitoutside anasyncfunction. This is a syntax error. Addasyncto the method. - Not handling rejections. An unhandled rejection appears in the browser console, and the component shows nothing to the user. Every imperative call needs a
catchor atry/catch. - Mutating the result. Treat returned data as read-only. For data from a
cacheable=truemethod, the platform may freeze it, and assigning to its fields throws in strict mode. Copy before changing, for examplethis.rows = result.map((row) => ({ ...row, selected: false })). - Placing slow work in
connectedCallbackwithout a guard. The component can be removed from the page before the Promise settles. Writing state afterward is harmless in most cases, but it wastes work. If the result matters only while the component is on screen, check a flag that you clear indisconnectedCallback. - Reading
error.messageonly. Errors from Apex usually carry the useful text inerror.body.message. The chapter on handling and displaying errors covers the full error shape.
Exercise
A component runs const a = await searchContacts({ searchTerm: 'A' }); const b = await searchContacts({ searchTerm: 'B' }); on a button click. Each call takes about 400 ms, and neither depends on the other. How would you change the code to shorten the wait, and what happens if the first call rejects in your new version?
Show answer
Start both calls together and wait once: const [a, b] = await Promise.all([searchContacts({ searchTerm: 'A' }), searchContacts({ searchTerm: 'B' })]);. The total wait drops from about 800 ms to about 400 ms, because the round trips overlap. If either call rejects, Promise.all rejects immediately with that first error, and the surrounding catch runs. The other call is not cancelled on the server, but its result is discarded. Use Promise.allSettled if you need both outcomes.
Exercise
A search box calls Apex on every change event. Sometimes the list shows results for an older search term. Why does this happen, and how does the request counter fix it?
Show answer
Network responses can arrive in a different order than the requests were sent, so a slow response for an older term can resolve after a fast response for a newer term and overwrite it. The counter gives each call an id and stores the latest id on the component. After the await, each call compares its own id to the latest id and discards its result if they differ, so only the answer to the most recent request updates the UI.