The JavaScript client library supports batching HTTP requests to make multiple API calls in one round-trip. For reference documentation about batch-related methods and classes, see Methods and Classes
The JavaScript client library defines an object called Batch
. You can start by instantiating this object:
const batch = gapi.client.newBatch();
Use the Batch
object's add
method to add individual HTTP requests. Only requests created via discovery should be added to a batch. The add
method supports one optional parameter:
Param | Type | Description |
---|---|---|
id
|
string | If an ID is supplied, the API attaches it to the response to this request. If no ID is supplied, the API generates a random ID. |
Example:
const getMe = gapi.client.people.people.get({
'resourceName': 'people/me'
});
const getYou = gapi.client.people.people.get({
'resourceName': 'people/you'
});
// Adding just the request
batch.add(getMe);
// Adding the request with an ID
batch.add(getYou, {'id': 'getYou'});
Batch requests are executed just like individual requests, using gapi.client.Batch.then
.
If the batch promise is fulfilled, the result field of the response will contain a batch response map. This map contains the responses to all requests in the batch, keyed by the ID of the request (either user-supplied or generated randomly by the client). The value is the API's response as a parsed JSON object.
Each request in the batch can also be treated as a promise. If the then
method is invoked on an individual request, the promise will be fulfilled or rejected with a value, just as if the request had been executed individually.
For more information about the response formats and using batch promises, see the Using Promises section.