Batch Ads
Fetch multiple ads in parallel with a single method call. Ideal for pre-loading ads or handling multiple contexts simultaneously.
Basic Usage
import Ads from 'notpixel';
const ads = new Ads({ publisherId: 'pub-xxx' });
const result = await ads.adsBatch({
inputs: ['query 1', 'query 2', 'query 3'],
});
console.log(result.ads); // Ad[]
console.log(result.success); // 3
console.log(result.failed); // 0
console.log(result.latencyMs); // total timeOptions
const result = await ads.adsBatch({
inputs: ['query 1', 'query 2', 'query 3'],
limit: 2, // max ads to return
dedupe: true, // remove duplicate ads (default: true)
publisherId: 'alt', // override publisher ID
});Response Type
interface AdsBatchResult {
ads: Ad[]; // Successfully fetched ads
success: number; // Count of successful fetches
failed: number; // Count of failed fetches
latencyMs: number; // Total time in ms
}All requests are made in parallel using Promise.allSettled, so one failure won’t affect others.
Deduplication
When dedupe: true (default), ads with the same ID are removed:
const result = await ads.adsBatch({
inputs: ['sql optimization', 'database performance', 'sql tuning'],
dedupe: true, // might return 2 unique ads instead of 3
});With Caching
Batch requests benefit from caching — if you’ve already fetched an ad for a query, it’ll be returned from cache:
const ads = new Ads({
publisherId: 'pub-xxx',
cache: true,
});
// First batch: 3 API calls
await ads.adsBatch({ inputs: ['a', 'b', 'c'] });
// Second batch: 0 API calls (all cached)
await ads.adsBatch({ inputs: ['a', 'b', 'c'] });
// Mixed: 1 API call (a, b cached, d is new)
await ads.adsBatch({ inputs: ['a', 'b', 'd'] });Error Handling
Failed requests are counted but don’t throw:
const result = await ads.adsBatch({
inputs: ['valid query', 'another query'],
});
if (result.failed > 0) {
console.warn(`${result.failed} ads failed to fetch`);
}
// Process successful ads
for (const ad of result.ads) {
console.log(ad.headline);
}Use Cases
- Pre-loading: Fetch ads for likely user queries ahead of time
- Multi-context: When a user message touches multiple topics
- A/B Testing: Fetch multiple ads and select the best one