2

I need to load a number of records more than the 2000 default limit for an SOQL query, but I need to wait until all of them are loaded before moving on. To do this, I make a request to get the total amount of records, and then I try to load 2000 at a time until my array size is the same as the number of records:

loadRecordData() {
  var allRecords = [];
  var offset = 0
  return getNumberOfRecords()
    .then(data => {
      const totalRecordCount = data[0].totalRecords
      while (allRecords.length !=== totalRecordCount) {
        console.log("CHECK 1");
        allRecords.push(this.loadIndexedRecords(offset));
        offset++;
      }

      // Now that all records have been loaded, I can work on them.
    }
  }
}

loadIndexedRecords(offset) {
  return getRecords({ offset: offset })
    .then(data => {
      console.log("CHECK 2");
      return data;
    })

}

With this, I would expect to see this in the console:

CHECK 1
CHECK 2
CHECK 1
CHECK 2
CHECK 1
CHECK 2
...

But instead It's just a bunch of CHECK 1's and the for loop never ends (I have a catch for this in my actual code).

How can I wait for the getRecords to return with the data before making the next call to getRecords? I tried using await, but I just get an error that I can't use await outside an async function.

How do you wait for calls to return when using APEX methods in Lightning Web Components?

0

1 Answer 1

1

I was able to make this work by combining the two APEX methods, getNumberOfRecords and getRecords into one APEX method that makes paged calls for me and returns one big array.

// JS File
loadRecordData() {
   return getRecords().then(data => { 
     // Now that all records have been loaded, I can work on them.
   });
}


// APEX File
@AuraEnabled
public static List<Object__c> getRecords() {
    Integer recordCount = Database.countQuery('SELECT Count() FROM Object__c');

    Integer recordLimit = 2000;
    Integer offset = 0;

    List<Object__c> records = new List<Object__c>();
    while(records.size() != recordCount) {
        List<Object__c> recs = [SELECT Id FROM Object__c LIMIT :recordLimit OFFSET :offset];
        records.addAll(recs);
        offset += recordLimit;
    }

    return records;
}
2
  • That won't work as written for more than 2000 records. There are better ways of pagination.
    – sfdcfox
    Mar 21, 2019 at 3:15
  • @sfdcfox Why won't this work if there are more than 2000 records? Please suggest a better solution rather than just saying there is a better solution
    – BlondeSwan
    Mar 21, 2019 at 14:49

You must log in to answer this question.

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