Best practice when using getReference

Hello,

I have a script that populates a field based on resolving a reference:

getReference(ctx.data.Tool.iv.Tool[0], function(tools) {
    var toolName = tools[0].data.Name.iv; // Took me by surprise that getReference returned an array!
    ctx.data.ToolNameOnArticle.iv = toolName;
    replace();
});

// change other fields
replace();

In this example the replace(); inside of getReference doesn’t have an effect and ToolNameOnArticle is not updated, presumably because the call is asynchronous so the replace(); at the end gets run before the getReference one does?

If so does it mean you should only run the getReference at the end of your script or would it be better to nest the rest of the script inside the callback (ours is getting quite large so that might look a bit odd…)?

Out of interest what if you want to make multiple getReference calls?

Have been using this for reference: https://docs.squidex.io/02-documentation/developer-guides/scripting#scripting-for-assets

replace() basically terminates the script. So you have to call it at the end. It it s a little bit ugly, but I could not find a better solution.

So you have two options:

  1. Nested calls
// Do X

getReference(..., function () {
   getReference(..., function () {
      getReference(..., function () {
         replace();
      });
   });
});

or reference counting (e.g. for loops)

// Do X

var expectedReferences = 10;
var pendingReferences = 10;

for (var i = 0; i < expectedReferences; i++) {
   getReference(..., function () {
      expectedReferences--;
      if (pendingReferences <= 0) {
        replace();
   });
}
1 Like

I have introduced a new getReferenceV2 which returns a single item (or null).

1 Like