Cantieri costruttori

I builder sono il modo standard per creare entità negli script Google Ads. I builder ti consentono di creare un'entità Google Ads in modo sincrono o asincrono. Puoi anche verificare se l'operazione è riuscita e intraprendere le azioni appropriate in base al risultato. Il seguente snippet di codice mostra come creare una parola chiave utilizzando un generatore.

// Retrieve your ad group.
let adGroup = AdsApp.adGroups().get().next();

// Create a keyword operation.
let keywordOperation = adGroup.newKeywordBuilder()
    .withCpc(1.2)
    .withText("shoes")
    .withFinalUrl("http://www.example.com/shoes")
    .build();

// Optional: examine the outcome. The call to isSuccessful()
// will block until the operation completes.
if (keywordOperation.isSuccessful()) {
  // Get the result.
  let keyword = keywordOperation.getResult();
} else {
  // Handle the errors.
  let errors = keywordOperation.getErrors();
}

Qualsiasi entità che può essere creata utilizzando gli script Google Ads lo fa utilizzando questo pattern dello strumento di creazione.

Considerazioni sul rendimento

Per impostazione predefinita, gli script Google Ads eseguono le operazioni in modo asincrono. In questo modo, gli script possono raggruppare le operazioni come batch e ottenere prestazioni elevate. Tuttavia, chiamare i metodi di operazione come isSuccessful() e getResult() forza gli script Google Ads a cancellare l'elenco delle operazioni in sospeso, il che potrebbe portare a prestazioni scadenti. Crea invece un array per contenere le operazioni, quindi esegui l'iterazione nell'array per recuperare i risultati.

Prestazioni scarse Prestazioni buone
for (let i = 0; i < keywords.length; i++)
  let keywordOperation = adGroup
    .newKeywordBuilder()
    .withText(keywords[i])
    .build();

  // Bad: retrieving the result in the same
  // loop that creates the operation
  // leads to poor performance.
  let newKeyword =
      keywordOperation.getResult();
  newKeyword.applyLabel("New keywords”);
}
// Create an array to hold the operations
let operations = [];

for (let i = 0; i < keywords.length; i++) {
  let keywordOperation = adGroup
    .newKeywordBuilder()
    .withText(keywords[i])
    .build();
  operations.push(keywordOperation);
}

// Process the operations separately. Allows
// Google Ads scripts to group operations into
// batches.
for (let i = 0; i < operations.length; i++) {
  let newKeyword = operations[i].getResult();
  newKeyword.applyLabel("New keywords”);
}