0

I have an AuraEnabled method which does a callout. I'd like to call this multiple times from my Aura component. How can I do this and then execute code after all of them have finished?

I tried doing $A.enqueueAction(...) in a loop but I couldn't see a way to have a callback for the whole thing.

1 Answer 1

2

You'd use Promise to do this. The method would look like:

// helper
  createRequest: function (method, params) {
    return new Promise(
      function (resolve, reject) {
        const event = component.get(method);
        event.setParams(params);
        event.setCallback(this, function(response) {
          if(response.getState() === 'SUCCESS') {
            resolve(response.getReturnValue());
          }
          if(response.getState() === 'ERROR') {
            reject(response.getError()?.[0]?.message || 'Unknown error');
          }
        });
      }
    )
  }

Now, you can call as many methods as you'd like:

Promise.allSettled(
  [1,2,3].map(
    (value)=>helper.createRequest('c.methodName', { value }) // { value: 1 }, etc
  )
).then(function(results) {
// results will have 3 items, one for each call
});

You must log in to answer this question.

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