2

In my controller I have an Init function that looks like this

   init: function (cmp, event, helper) {
    cmp.set('v.mycolumns', [
        { label: 'Document Name', fieldName: 'Name', type: 'text'},
        { label: 'Document Link', fieldName: 'Community_URL__c', type: 'url', typeAttributes: {label: 'Visit Link', target: '_self' }}
    ]);
    helper.getUser(cmp);
    helper.getData(cmp);
    helper.getDocumentGroupName(cmp);
    helper.getDocumentGroupId(cmp);
    helper.getDocumentGroup(cmp);
    helper.getObjectById(cmp);
}

Long story short I want to force helper.getObjectById to wait until the prior function helper.getDocumentGroup has completed.

I set an attribute in the getDocumentGroup function and then reference that component attribute in getObjectById. When I debug I can see that the getObjectById is trying to reference the attribute prior to it being set in getDocumentGroup. So they must both be running at the same time rather than in a chain sequence.

How do I say run helper.getDocumentGroup first and then when complete run helper.getObjectbyId next?

7

You use Promises if you need asynchronous code to appear synchronous. From a practical standpoint, that means you write something like this:

helper.getUser(cmp)
  .then(() => helper.getData(cmp))
  .then(() => helper.getDocumentGroupName(cmp))
  .then(() => helper.getDocumentGroupId(cmp))
  .then(() => helper.getDocumentGroup(cmp))
  .then(() => helper.getObjectById(cmp))
  .catch(error => helper.displayError(error));

Each method returns a Promise, like this:

getData: function(cmp) {
  return new Promise(
    $A.getCallback((resolve, reject) => {
      // your logic goes here
    })
  );
}

Each time you call the server, the area where "your logic goes here" should call either resolve or reject. On resolve, you go to the next promise. On reject, your code goes to the catch statement, and you can display the error. You can consolidate this down further if you like, but this is the general pattern you'd use to make sure things are called in order. You should only do this for items that actually matter, of course, since there is a performance penalty for hitting the server frequently like this.

Also, see this question for more info.

Your Answer

By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.