构建器是在 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”); } |