Version 1.0.1 is now available! Looking for a migration guide?
v1.0.1
/
  • Get Started
  • Working
  • GitHub
  • Overview
  • Introduction
  • Actions
  • Call
  • Call
  • CallList
  • CallList
  • FetchList
  • FetchList
  • Batch
  • Batch
  • BatchByChunk
  • BatchByChunk
  • Tools
  • HealthCheck
  • Ping
  • Logger
  • Logger
  • Telegram
  • Limiters
  • Limiters
  • B24Frame
  • Introduction
  • Initialization
  • Auth
  • Dialog
  • Options
  • Parent
  • Placement
  • Slider
  • b24ui
  • b24icons
v1.0.1
  • Get started
  • Working

BatchByChunkV2.make

Method for executing batch requests with automatic chunking for any number of commands. Automatically splits large command sets into batches of 50 and executes them sequentially. Use only arrays of tuples or arrays of objects.
BatchByChunkV2
AjaxResult
AjaxError
SdkError
We are still updating this page. Some data may be missing here — we will complete it shortly.

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
// 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:

ParameterTypeRequiredDescription
callsBatchCommandsArrayUniversal | BatchCommandsObjectUniversalYesCommands to execute in the batch. Supports several formats. Named commands are not supported.
optionsOmit<IB24BatchOptions, 'returnAjaxResult'>NoAdditional options for batch request execution.

Command Formats (options.calls)

1. Array of tuples (BatchCommandsArrayUniversal)

calls: [
  ['method1', params1],
  ['method2', params2],
  // ...
]

2. Array of objects (BatchCommandsObjectUniversal)

calls: [
  { method: 'method1', params: params1 },
  { method: 'method2', params: params2 },
  // ...
]

Batch Request Options (options.options)

OptionTypeDefaultDescription
isHaltOnErrorbooleantrueWhether to stop execution on the first error in a chunk.
requestIdstring—Unique request identifier for tracking. Used for request deduplication and debugging.

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:

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

BatchByChunkCrmItems.ts
import type { AjaxResult } from '@bitrix24/b24jssdk'
import { 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 as Result<AjaxResult<{ item: Deal }>[]>).getData()!
  const results: number[] = []
  resultData.forEach((resultRow, index) => {
    if (resultRow.isSuccess) {
      results.push(resultRow.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 Call for single calls.
  • For working with lists: Use CallList for retrieving large volumes of data.
  • For step-by-step processing: Use FetchList for processing data as it arrives.
  • For batch operations: Use Batch to execute up to 50 commands in a single request.
  • On the client-side (browser): Use the built-in B24Frame object.

Batch

Method for executing batch requests to Bitrix24 REST API version 2. Allows executing up to 50 commands in a single API call.

HealthCheck

Method for checking the availability of Bitrix24 REST API. Performs a simple request to the REST API to verify service health.

On this page

  • Overview
  • Method Signature
    • Parameters
    • Command Formats (options.calls)
    • Batch Request Options (options.options)
    • Return Value
  • Error Handling
  • Examples
    • Bulk CRM deal creation
  • Alternatives and Recommendations
Releases
Published under MIT License.

Copyright © 2024-present Bitrix24