async/await functions in LWC
async/await
syntax is fully supported by LWC. However, as it was introduced in ES8, in old browsers, this syntax is transpiled down to ES5, which can cause performance issues if the code is executed many times.
the
await
keyword is only valid insideasync
functions
In your case to make your code deployable with using async/await syntax
you can use 3 approaches:
- Declare some
async init()
function and invoke it withinconnectedCallback()
hook:
connectedCallback() {
this.init();
}
async init() {
try {
this.accounts = await getAll();
const value = await this.promiseFunc();
console.log('2nd then executes after 3 seconds async, value:' + value);
} catch (error) {
this.error = error;
} finally {
this.isLoaded = true;
}
}
- Invoke it anonymously as an
IIFE
:
connectedCallback() {
(async () => {
try {
this.accounts = await getAll();
const value = await this.promiseFunc();
console.log('2nd then executes after 3 seconds async, value:' + value);
} catch (error) {
this.error = error;
} finally {
this.isLoaded = true;
}
})();
}
- Make your
connectedCallback()
lifecycle hookasync
:
async connectedCallback() {
try {
this.accounts = await getAll();
await this.errorPromise();
const value = await this.promiseFunc();
console.log('2nd then executes after 3 seconds async, value:' + value);
} catch (error) {
this.error = error;
} finally {
this.isLoaded = true;
}
}
I wouldn't recommend you to use the 3rd option at least for API consistency. Not sure about long term effects.
As for catching errors of async functions you can use try/catch
block or handle them separately, using catch()
method because async function implicitly returns a promise:
this.accounts = await getAll().catch(error => this.error = error);
const value = await this.promiseFunc().catch((/*rejected obj*/) => /*error handling*/);