Overview
Use BatchByChunkV2.make() to execute a large number of REST API requests with automatic batching.
The method returns a Promise with a Result<T[]> object containing the combined results of all successful commands.
This is especially useful for:
- Bulk creating or updating records
- Exporting large volumes of data via batch requests
- Performing complex operations that require many different API calls
// @check-ignore: full example — BatchCommands Array.from tuple inference and fields not in TypeCallParams
// Basic usage
import { B24Hook, EnumCrmEntityTypeId } from '@bitrix24/b24jssdk'
// We create 150 deals (they will be divided into 3 chunks of 50 deals each)
const commands = Array.from({ length: 150 }, (_, i) => [
'crm.item.add',
{ entityTypeId: EnumCrmEntityTypeId.deal, fields: { title: `Deal ${i + 1}` } }
])
const response = await $b24.actions.v2.batchByChunk.make({
calls: commands,
options: {
isHaltOnError: true,
requestId: 'unique-request-id'
}
})
Method Signature
make<T = unknown>(
options: ActionBatchByChunkV2
): Promise<Result<T[]>>
Parameters
The options object contains the following properties:
Command Formats (options.calls)
1. Array of tuples (BatchCommandsArrayUniversal)
// @check-ignore: partial snippet — calls array literal, not a valid statement
calls: [
['method1', params1],
['method2', params2],
// ...
]
2. Array of objects (BatchCommandsObjectUniversal)
// @check-ignore: partial snippet — object array literal, not a valid statement
calls: [
{ method: 'method1', params: params1 },
{ method: 'method2', params: params2 },
// ...
]
Batch Request Options (options.options)
Return Value
Promise<CallBatchResult<T>> — a promise that resolves to a Result<T[]> object.
Important features:
- Only successful results: Only successfully executed commands are included in the array.
- Combined array: All results from all chunks are combined into a single array.
- Order preserved: Results are preserved in the same order as the original commands.
Error Handling
The method will split all commands into chunks and begin executing them one by one using Batch.
If an error occurs when calling Batch, it will be stored in Result, and the loop will continue executing.
The isHaltOnError parameter affects the behavior of the callBatch method:
When isHaltOnError = false, commands are executed even if some have completed with an error.
When isHaltOnError = true (the default), package execution is aborted if an error occurs in any of the commands.
Always check the result using isSuccess and handle errors:
// @check-ignore: top-level return in error-handling illustration
const calls = Array.from({ length: 150 }, (_, i) => [
'crm.item.add',
{ entityTypeId: EnumCrmEntityTypeId.deal, fields: { title: `Deal ${i + 1}` } }
])
const response = await $b24.actions.v2.batchByChunk.make({
calls,
options: {
isHaltOnError: true,
requestId: 'unique-request-id'
}
})
if (!response.isSuccess) {
// Handling error
console.error(new Error(`Error: ${response.getErrorMessages().join('; ')}`))
return
}
// Working with a successful result
const data = response.getData()
Examples
Bulk CRM deal creation
// @check-ignore: full example — BatchCommands Array.from tuple inference and fields not in TypeCallParams
import { AjaxError, B24Hook, EnumCrmEntityTypeId, LoggerFactory } from '@bitrix24/b24jssdk'
type Deal = {
id: number
title: string
stageId: string
opportunity: number
}
const devMode = !!(typeof import.meta !== 'undefined' && (import.meta.dev || import.meta.env?.DEV))
const $logger = LoggerFactory.createForBrowser('Example:batchByChunkCrmItems', devMode)
const $b24 = B24Hook.fromWebhookUrl('https://your_domain.bitrix24.com/rest/1/webhook_code/')
async function addMultipleItems(needAdd: number, requestId: string): Promise<number[]> {
const calls = Array.from({ length: needAdd }, (_, i) => [
'crm.item.add',
{
entityTypeId: EnumCrmEntityTypeId.deal,
fields: {
title: `Automatic deal #${i + 1}`,
stageId: 'NEW',
opportunity: Math.floor(Math.random() * 10000) + 1000
}
}
])
const response = await $b24.actions.v2.batchByChunk.make<{ item: Deal }>({
calls,
options: {
isHaltOnError: true,
requestId
}
})
if (!response.isSuccess) {
throw new Error(`Problem: ${response.getErrorMessages().join('; ')}`)
}
const resultData = response.getData() ?? []
const results: number[] = resultData.map(chunkRow => chunkRow.item.id)
return results
}
// Usage
const requestId = 'batch/crm.item.add'
try {
const needAdd = 120
const items = await addMultipleItems(needAdd, requestId)
$logger.info(`Retrieved ${items.length} items`, {
expected: needAdd,
retrieved: items.length,
items
})
} catch (error) {
if (error instanceof AjaxError) {
$logger.critical(error.message, { requestId, code: error.code })
} else {
$logger.alert('Problem', { requestId, error })
}
}
Alternatives and Recommendations
- For sequential requests: Use
Callfor single calls. - For working with lists: Use
CallListfor retrieving large volumes of data. - For step-by-step processing: Use
FetchListfor processing data as it arrives. - For batch operations: Use
Batchto execute up to 50 commands in a single request. - On the client-side (browser): Use the built-in
B24Frameobject.