Builder

Builder adalah cara standar untuk membuat entity di skrip Google Ads. Builder memungkinkan Anda membuat entity Google Ads secara sinkron atau asinkron. Anda juga dapat memeriksa apakah operasi berhasil atau tidak, dan mengambil tindakan yang sesuai bergantung pada hasil operasi. Cuplikan kode berikut menunjukkan cara membuat kata kunci menggunakan builder.

// 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();
}

Setiap entity yang dapat dibuat menggunakan skrip Google Ads akan melakukannya menggunakan pola builder ini.

Pertimbangan performa

Secara default, skrip Google Ads menjalankan operasinya secara asinkron. Hal ini memungkinkan skrip mengelompokkan operasi Anda sebagai batch, dan mencapai performa tinggi. Namun, memanggil metode Operasi seperti isSuccessful() dan getResult() akan memaksa skrip Google Ads untuk menghapus daftar operasi yang tertunda, dan dengan demikian dapat menyebabkan performa buruk. Sebagai gantinya, buat array untuk menyimpan operasi, lalu ulangi array tersebut untuk mengambil hasilnya.

Performa buruk Performa baik
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");
}