1

In LWC JS, I am making an external API call-out and an Apex method and accumulating the results. How to synchronizes the process?

Example:

renderedCallback(){
  let a,b;
  getApiResult().then(result => {
      this.a = result;
   })
  apexMethod().then(result=>{
      this.b = this.a + result;
  })
  console.log(a+b);
}

How can get the value of a into the apexMethod? And also consider the logging result at the end.

2 Answers 2

4

You can go by what Rahul has suggested, its called as Promise chaining.

Modern javascript has new concepts that allow you to handle these complex requirements without making you go in promise chaining callback hell.

Welcome Async and Await :)

await - > The keyword await makes JavaScript wait until that promise settles and returns its result.

async - > The word “async” before a function means one simple thing: a function always returns a promise. Other values are wrapped in a resolved promise automatically.

So your code will be something like:

async function doComplexCallout() {
    let responseFromApi1 = await fetch('https://salesforce.stackexchange.com/');
    let responseFromApi2 = await doApexCall(responseFromApi1.data); //sending response of first call to second.

}

Async and await are completely supported by lwc and modern browser as mentioned here async/await functions in LWC

src: https://javascript.info/async-await

Regarding logging: You can put the code of async function inside the try-catch block and log whenever error happens and promise is not resolved.

Src: https://itnext.io/error-handling-with-async-await-in-js-26c3f20bc06a

3

The first thing, be sure that you want to perform this in renderedCallback, because it runs very frequent. This runs every time your component is rendered on events like @track, @api, @wire are properties updated.

to make successive promises you can do like this.

renderedCallback() {
    let a, b;
    getApiResult().then(result => {
        this.a = result;
        apexMethod().then(result => {
            this.b = this.a + result;
            console.log(a + b);
        })
    })
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .