Quantcast
Channel: Imperative Call Using Await In LWC - Salesforce Stack Exchange
Viewing all articles
Browse latest Browse all 3

Answer by sfdcfox for Imperative Call Using Await In LWC

$
0
0

@wire doesn't make the function async. To be async means to behave like a Promise. In other words, a function marked with this keyword transforms from:

async method() {  try {    const result = await doSomething();    return result;  } catch(e) {    handleError(e);  }}

to something like:

method() {  return new Promise((resolve, reject) =>    doSomething().then(resolve).catch((e) => {      handleError(e);      reject(e);    })  );}

As far as making it more legible, use early returns when appliable.

@wire(getRecord, { recordId: '$recordId', fields: RECORD_FIELDS })async wiredRecord({ error, data }) {    if (error) {        console.log(error);        return null;    }    if(!data) {        return null;    }    try {        const moreData = await fetchMoreData({ recordId: data.fields.Id.value });        doStuff();    } catch (error) {        console.log(error);    }}

Keep in mind that you can do multiple things in a single try-catch:

    try {        const moreData = await fetchMoreData({ recordId: data.fields.Id.value });        doStuff();        const yetMoreData = await fetchEvenMoreData(params);    } catch (error) {        console.log(error);    }

That's the advantage of using async over traditional promises.


Viewing all articles
Browse latest Browse all 3

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>