Return an array of records from linked record IDs?

Hello! Hoping you all can help.

I have a base of Store Locations (name, address, website) and a related table of Deals (details, participating store locations).

The Deals have a linked record field, Participating Store Locations, to attach one or more Store Locations records to each Deal.

I need to display a list of Deals with the details for each Participating Store Location like this:

DEAL 1

  • Participating Store 1
  • Participating Store 2

DEAL 2

  • Participating Store 3
  • Participating Store 4
  • Participating Store 5

I can get a list of the Participating Store Location record IDs for the store locations from the linked record field.

I am having trouble getting the Store Location records returned from the find function. I think it has something to do with the timing of an asynchronous function.

I’ve tried a few things to make a callback or promise work but my javascript is thin in that area and I can’t get it to work.

Any help is greatly appreciated. Thanks!

Here is the code:

var storeLocationIDs = {}; 
var storeLocationRecords = [];

base('Deals').select({
    maxRecords: 100,
    view: "Active Deals"
    }).eachPage(function page(records, fetchNextPage) {

    records.forEach(function(record) {
         
        storeLocationIDs = record.get('Participating Locations');
        console.log('Participating Locations: ', storeLocationIDs ); // Displays IDs for participating locations

        for ( i=0 ; i < storeLocationIDs.length ; i++ ) {
 	
          base('Store Locations').find(storeLocationIDs[i], function(err, record) {
   			 if (err) { console.error(err); return; }
             storeLocationRecords.push(record);
             console.log('storeLocationRecords = ', storeLocationRecords); // Displays record objects
          });

        };
      
    });

    fetchNextPage();

}, function done(err) {
    if (err) { console.error(err); return; }
});
  
function listDeals () { 
    console.log('listDeals storeLocationRecords = ', storeLocationRecords[0]); // Displays UNDEFINED but expected first Record
    };
      
listDeals ();

The first thing that I noticed about your code is that you have a lot of nested functions going on.

Have you considered refactoring the code to reduce the nesting? Break the code into two stage. In stage one, gather all of the deals and the linked record ids for the locations. Then in stage two, just gather the information for the location. Finally, present all the assembled data to your users.

Yes, you’re right. I am trying to get it working first by modifying the example code from the API. Then I am going to restructure it to make it easier to manage.

I recommend restructuring the code first. You may find that it is easier to get the code to work that way.

This topic was solved and automatically closed 15 days after the last reply. New replies are no longer allowed.