Do not combine then and await in LWC

Do Not Combine Then And Await in LWC

The code is confusing. Devs who are not familiar with Promises very well, will not follow the code flow. It's hard to understand. Why do we need “await“ if there is “then“? What is the…

JavaScript allows combining “then/catch“ and “async/await“. You can do something like this:

Don't do this
const myPromise = new Promise((resolve, reject) => setTimeout(() => resolve({
    message: 'It works!'
}), 200));

async function myCombinedFuntion() {
    await myPromise().then(result => {
        // ...
    });
}

But is it a good practice to use “then“ and “await“ together?

You should NOT combine “then/catch“ and “async/await“

The code is confusing. Devs who are not familiar with Promises very well, will not follow the code flow. It's hard to understand. Why do we need “await“ if there is “then“? What is the idea behind it? Keep It Simple, Stupid (KISS) rule is broken here. You do NOT need constructions like that in your code. Do not mix “then“ and “await“ for the same Promise.

Choose what is better for your code and stick to it.

Do this
const myPromise = new Promise((resolve, reject) => setTimeout(() => resolve({
    message: 'It works!'
}), 200));

async function myAwaitFunction() {
    try {
        const result = await myPromise();
        // ...
    } catch(error) {
        console.error(error);
    }
}

function myThenFunction() {
    myPromise().then(result => {
        // ...
    }).catch(error => {
        console.error(error);
    });
}

Text and code were extracted from the original slide. Plain-text version of the whole catalog