@todo fix me!
v1.0.1
  • Get Started
  • Templates
  • GitHub
  • Overview
  • B24Hook
  • Methods
  • callMethod
  • callFastListMethod
  • fetchListMethod
  • callBatch
  • callBatchByChunk
  • getTargetOrigin
  • getTargetOriginWithPath
  • getLogger
  • setLogger
  • destroy
  • getHttpClient
  • offClientSideWarning
  • Getters
  • auth
  • isInit
  • b24ui
  • b24icons
v1.0.1
  • Docs
  • Frame
  • Hook
  • OAuth
  • Templates

B24Hook.callBatchByChunk()

Use B24Hook.callBatchByChunk() to execute batch requests to the Bitrix24 REST API with any number of commands. The method automatically splits a large list of commands into chunks of 50 commands each (the maximum size of a single batch in Bitrix24) and executes them sequentially. Works only in a server environment.
B24Hook
TypeB24
The B24Hook object is intended exclusively for use on the server.
  • A webhook contains a secret access key, which MUST NOT be used in client-side code (browser, mobile app).
  • For the client side, use B24Frame.

Quick Overview

Use callBatchByChunk() to execute a large number of API commands (more than 50). The method automatically manages command chunking, sequential execution, and result aggregation.

This is especially useful for:

  • Bulk creating or updating hundreds or thousands of 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'

const $b24 = B24Hook.fromWebhookUrl('https://your_domain.bitrix24.com/rest/1/webhook_code/')

// We create 150 teams (they will be divided into 3 chunks of 50 teams each)
const batchCalls = Array.from({ length: 150 }, (_, i) => [
  'crm.item.add',
  { entityTypeId: EnumCrmEntityTypeId.deal, fields: { title: `Deal ${i + 1}` } }
])

const response = await $b24.callBatchByChunk(batchCalls, false)

Method Signature

callBatchByChunk(
  calls: Array<[string, object?]>,
  isHaltOnError: boolean
): Promise<Result>

Parameters

ParameterTypeRequiredDescription
callsArray<[string, object?]>YesAn array of commands to execute. Format: [[method, params], [method, params]]. The total number of commands can be any (more than 50).
isHaltOnErrorbooleanNoThe method will always execute all chunks. If an error occurs when calling callBatch, it will be saved in Result, and the loop will continue execution. The isHaltOnError parameter affects the behavior of the callBatch method:
- If isHaltOnError = false, commands are executed even if some fail.
- If isHaltOnError = true (the default), batch execution is aborted if an error occurs in any of the commands.

Return Value

Promise<Result> — a promise that resolves to a Result object. This object provides:

  • .getData(): any[] — returns response data. An array of chunked results, where each element contains the results of one chunk.
  • .isSuccess: boolean — a flag indicating whether all chunks were successfully executed (no errors in all chunks).
  • .getErrorMessages(): string[] — an array of error messages.

Key Concepts

Automatic Chunking

This method automatically splits the input command array into chunks of 50 elements:

  • Chunk 1: commands 0-49
  • Chunk 2: commands 50-99
  • Chunk 3: commands 100-149
  • and so on.

Each chunk is executed as a separate batch request using callBatch.

Sequential Execution

callBatchByChunk executes chunks sequentially, one after another. This is important for:

  • Predictable execution
  • Easier debugging

Important Limitations

  • Does not support dependencies between commands: Do not use references between commands ($result[SomeCommand][item][id]), as the method does not support dependencies between commands in different chunks.
  • Execution Time Limits: Total execution time = number of chunks × execution time of one chunk. Take into account script execution time limits on the server.
  • API Limits: Each chunk counts as one API request.

Error Handling

The method will split all commands into chunks and begin executing them one by one using callBatch.

If an error occurs when calling callBatch, 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 (the default), commands are executed even if some have completed with an error.
  • When isHaltOnError = true, package execution is aborted if an error occurs in any of the commands.

Always check the result with isSuccess and handle errors appropriately.

import { B24Hook, EnumCrmEntityTypeId } from '@bitrix24/b24jssdk'

const $b24 = B24Hook.fromWebhookUrl('https://your_domain.bitrix24.com/rest/1/webhook_code/')

const batchCalls = Array.from({ length: 150 }, (_, i) => [
  'crm.item.add',
  { entityTypeId: EnumCrmEntityTypeId.deal, fields: { title: `Deal ${i + 1}` } }
])

const response = await $b24.callBatchByChunk(batchCalls, false)

if (!response.isSuccess) {
  // Handling API error
  console.error(new Error(`API Error: ${response.getErrorMessages().join('; ')}`))
  return
}

// Working with a successful result
const data = response.getData()

Examples

Bulk trade creation

MassDealCreation.ts
import type { BatchCommandsArrayUniversal } from '@bitrix24/b24jssdk'
import { B24Hook, EnumCrmEntityTypeId, LoggerFactory } from '@bitrix24/b24jssdk'

type Deal = {
  id: number
  title: string
  stageId: string
  opportunity: number
  assignedById: number
}

const devMode = typeof import.meta !== 'undefined' && (globalThis._importMeta_.env?.DEV || false)
const $logger = LoggerFactory.createForBrowser('Example:MassDealCreation', devMode)
const $b24 = B24Hook.fromWebhookUrl('https://your_domain.bitrix24.com/rest/1/webhook_code/')

try {
  // We create an array of commands to create 120 trades.
  const dealCreationCalls: BatchCommandsArrayUniversal<string, Record<string, any>> = Array.from({ length: 120 }, (_, i) => [
    'crm.item.add',
    {
      entityTypeId: EnumCrmEntityTypeId.deal,
      fields: {
        title: `Automatic deal #${i + 1}`,
        stageId: 'NEW',
        opportunity: Math.floor(Math.random() * 10000) + 1000,
        assignedById: 1 // ID of the responsible person
      }
    }
  ])

  $logger.info(`Creating ${dealCreationCalls.length} deals...`)

  const response = await $b24.callBatchByChunk<{ item: Deal }>(dealCreationCalls, { isHaltOnError: true })

  if (!response.isSuccess) {
    throw new Error(`API Error: ${response.getErrorMessages().join('; ')}`)
  }

  const data = response.getData()!

  // Collect the IDs of all created transactions
  const createdDealIds: number[] = []
  data.forEach((chunkRow) => {
    createdDealIds.push(chunkRow.item.id)
  })

  $logger.info('Created deals with ID', {
    createdDealIds
  })
} catch (error) {
  $logger.error('some error', { error })
}

Bulk contact update

MassContactUpdate.ts
import type { BatchCommandsArrayUniversal } from '@bitrix24/b24jssdk'
import { B24Hook, EnumCrmEntityTypeId, LoggerFactory } from '@bitrix24/b24jssdk'

type Contact = {
  id: number
  name: string
  lastName: string
}

const devMode = typeof import.meta !== 'undefined' && (globalThis._importMeta_.env?.DEV || false)
const $logger = LoggerFactory.createForBrowser('Example:BatchObject', devMode)
const $b24 = B24Hook.fromWebhookUrl('https://your_domain.bitrix24.com/rest/1/webhook_code/')

try {
  // First, we get all the contacts that need to be updated.
  const contactResponse = await $b24.callFastListMethod<Contact>('crm.item.list', {
    entityTypeId: EnumCrmEntityTypeId.contact,
    filter: { '=sourceId': 'WEBFORM' }, // Contacts from web forms
    select: ['id', 'name', 'lastName', 'sourceId']
  }, 'id', 'items')

  if (!contactResponse.isSuccess) {
    throw new Error(`Failed to retrieve contact list: ${contactResponse.getErrorMessages().join('; ')}`)
  }

  const contacts: Contact[] = contactResponse.getData() || []

  if (contacts.length === 0) {
    $logger.warning('No contacts to update')
  } else {
    $logger.info(`Contacts found for update: ${contacts.length}`)

    // Create commands to update each contact
    const updateCalls: BatchCommandsArrayUniversal<string, Record<string, any>> = contacts.map(contact => [
      'crm.item.update',
      {
        entityTypeId: EnumCrmEntityTypeId.contact,
        id: contact.id,
        fields: {
          // Example: Adding a prefix to a name
          name: `[UPDATED] ${(contact.name || '').replace('[UPDATED] ', '')}`.trim(),
          comments: `Automatic update from ${new Date().toLocaleDateString('en')}`
        }
      }
    ])

    // We perform the update in chunks
    const response = await $b24.callBatchByChunk<{ item: Contact }>(updateCalls, { isHaltOnError: false }) // Continue with errors

    if (!response.isSuccess) {
      throw new Error(`API Error: ${response.getErrorMessages().join('; ')}`)
    }

    const data = response.getData()!
    const updatedContactIds: number[] = []
    data.forEach((chunkRow) => {
      updatedContactIds.push(chunkRow.item.id)
    })

    $logger.info('Contacts with ID updated', {
      length: updatedContactIds.length,
      updatedContactIds: updatedContactIds.join(', ')
    })
  }
} catch (error) {
  $logger.error('some error', { error })
}

Alternatives and Recommendations

  • For small batches (up to 50 commands): Use callBatch - it's simpler.
  • To get the entire list in memory: Use callFastListMethod, which returns the entire array of data.
  • On the client (browser): Use the built-in B24Frame object instead of B24Hook.
  • For very large data volumes (thousands of records):
    • Split operations into multiple separate script runs
    • Use a task queue for background processing

References

  • Result — Documentation for the result object.
  • Official Bitrix24 REST API Documentation — Reference for all available methods.
  • Working with Large Volumes of Data — Recommendations for optimizing code to retrieve large data.

callBatch

Use B24Hook.callBatch() to execute batch requests to the Bitrix24 REST API. This allows you to execute up to 50 different commands in a single HTTP request, significantly increasing performance for bulk data operations. Works only in server environment.

getTargetOrigin

Use B24Hook.getTargetOrigin() to get Bitrix24 address. Works only in server environment.

On this page

  • Quick Overview
  • Method Signature
    • Parameters
    • Return Value
  • Key Concepts
    • Automatic Chunking
    • Sequential Execution
    • Important Limitations
    • Error Handling
  • Examples
    • Bulk trade creation
    • Bulk contact update
  • Alternatives and Recommendations
  • References
Releases
Published under MIT License.

Copyright © 2024-present Bitrix24