Sub topic 5
Working with the returned Promise
This chapter assumes you can read basic JavaScript, including ES modules and Promises. It also assumes you know how to import an Apex method into a Lightning Web Component and call it from an event handler. Here you will learn what an imperative Apex call returns and how to consume it correctly.
What the call returns
When you import an Apex method, you get a function. Calling that function does not return the data. It returns a Promise, which is an object that represents a result that will arrive later.
A Promise is in one of three states:
- Pending: the server request is still in progress.
- Fulfilled: Apex returned a value, and the Promise resolves with it.
- Rejected: the call failed, and the Promise rejects with an error object.
A Promise settles only once. After it is fulfilled or rejected, its state does not change.
Using async/await
The await keyword pauses the function until the Promise settles. It then gives you the resolved value. A function that uses await must be declared async.
import { LightningElement } from 'lwc';
import searchContacts from '@salesforce/apex/ContactController.searchContacts';
export default class ContactSearch extends LightningElement {
searchTerm = '';
contacts = [];
errorMessage;
async handleSearch() {
try {
this.contacts = await searchContacts({ searchTerm: this.searchTerm });
} catch (error) {
this.contacts = [];
this.errorMessage = error?.body?.message || error?.message || 'Unknown error';
}
}
}Two things to notice:
- Parameters go in a single object, keyed by the Apex parameter name.
- A rejected Promise throws at the
awaitline, so atry/catchblock catches it.
Using then/catch
You can get the same result by chaining methods on the Promise.
handleSearch() {
searchContacts({ searchTerm: this.searchTerm })
.then((result) => {
this.contacts = result;
this.errorMessage = undefined;
})
.catch((error) => {
this.contacts = [];
this.errorMessage = error?.body?.message || error?.message || 'Unknown error';
})
.finally(() => {
this.isLoading = false;
});
}The then callback runs on success. The catch callback runs on rejection. The finally callback runs in both cases, which makes it a good place for cleanup.
| Style | Strength | Watch out for |
|---|---|---|
| async/await | Reads top to bottom, works with `try/catch` | Forgetting `async` or `await` |
| then/catch | Fits short, single-step calls | Nesting grows with dependent calls |
Both styles are valid. Pick one and use it consistently in a component.
Common errors
- Forgetting
await. Without it,this.contactsholds a Promise, not an array. The template renders nothing useful, and no error appears. - Passing the parameter directly. Writing
searchContacts(this.searchTerm)sends the wrong shape. UsesearchContacts({ searchTerm: this.searchTerm }). - Skipping error handling. A rejection with no
catchis an unhandled rejection. The user sees no feedback, and the failure surfaces only in the browser console. - Mutating the result. Data returned from Apex may be read-only if it came from a cacheable method. Copy it before changing it, for example with
[...result]or{ ...record }.
Running calls in parallel
Awaiting two independent calls one after the other makes them run in sequence. If neither depends on the other, start both and wait for them together.
async loadAll() {
const [contacts, accounts] = await Promise.all([
searchContacts({ searchTerm: this.searchTerm }),
searchAccounts({ searchTerm: this.searchTerm })
]);
this.contacts = contacts;
this.accounts = accounts;
}Promise.all rejects as soon as any one call rejects. Handle that with a single try/catch around it.
Exercise
A developer writes this.contacts = searchContacts({ searchTerm: this.searchTerm }); inside a handler, and the list stays empty with no error. What is wrong, and how do you fix it?
Show answer
The call returns a Promise, and the code assigns the Promise itself to this.contacts. Make the handler async and write this.contacts = await searchContacts({ searchTerm: this.searchTerm });, inside a try/catch. Alternatively, assign the result inside a .then() callback.
Exercise
Which Promise method runs whether the call succeeds or fails, and why is it useful?
Show answer
finally. It runs after either outcome, so it is the right place for cleanup such as turning off a loading flag, without repeating the code in both the success and error paths.