建造者

建構工具是在 Google Ads 指令碼中建立實體的標準方式。您可以使用建構工具,以同步或非同步的方式建立 Google Ads 實體。您也可以檢查作業是否成功,並根據作業結果採取適當行動。下列程式碼片段說明如何使用建構工具建立關鍵字。

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

任何可以透過 Google Ads 指令碼建立的實體,都會採用這種建構工具模式。

效能注意事項

根據預設,Google Ads 指令碼會以非同步方式執行作業。這可讓指令碼將作業按批次分組,進而實現高效能。不過,呼叫 Operation 方法 (例如 isSuccessful()getResult()) 會強制 Google Ads 指令碼清除其待處理作業清單,因此可能導致效能不佳。請改為建立陣列存放運算,然後對該陣列進行疊代作業來擷取結果。

效能不佳 效能良好
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”);
}