构建器

构建器是在 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 脚本会异步执行各项操作。这允许脚本将操作按批次分组,并实现高性能。但是,调用 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”);
}