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:
var batch = gapi.client.newBatch();
Use the Batch
object's add
method to add individual HTTP requests. 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:
var searchRequest = function(name) {
return gapi.client.request({
'path': 'plus/v1/people',
'params': {'query': name}
});
};
var searchAlvin = searchRequest('Alvin');
var searchSimon = searchRequest('Simon');
// Adding just the request
batch.add(searchAlvin);
// Adding the request with an ID
batch.add(searchSimon, {'id': 'searchSimon'});
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.