建構工具是 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”); } |