Using Promises

A JavaScript promise represents the result of an asynchronous operation. Promises
can be in one of three states, pending, fulfilled, or rejected. To access a promise's
fulfilled value or rejection reason, register your handler to the promise's then
method.

The JavaScript client library provides a Promises/A+-conformant
interface. We strongly recommend that you use promises instead of callbacks.
Requests made using the promise interface are RESTful.
Using promises also gives you elegant error handling and easy chaining, and the Google
JavaScript promise interface fixes various small bugs and inconsistencies that were present
in the older callback-based interface.

Using promises

Requests created through gapi.client.request,
gapi.client.newBatch, and registered API methods are "thenable."
gapi.client.load also returns a promise if a callback argument is not provided.
Each of the requests has a then(opt_onFulfilled, opt_onRejected, opt_context)
method that takes three optional parameters:

Parameter

Type

Description

opt_onFulfilled(response)

function

Optional fulfilled promise handler.

opt_onRejected(reason)

function

Optional rejected promise handler.

opt_context

object

Optional context for the handlers to execute in.

Note: The promises in this library are resolved lazily. That means that no
network requests are actually made until then is invoked. Once a promise is
resolved or rejected with a value, the value does not change.

Note: We strongly recommended that you always provide a rejection handler. Rejections that your code
does not handle are propagated as top-level exceptions. Rejection reasons can include
application-level errors and network errors.

Fulfilled responses and application-level rejections are in the following format:

Batch requests

When you create a request with the intention of adding it to a batch, do not invoke its
then method until after the request has been added to the batch.
If the then method is invoked before the request is added,
the request is sent immediately instead of as part of the batch.
You can invoke the requests's then method before or after the batch's
then. The optional callback parameter to the add
method has no effect when the batch object is treated as a promise.

Migrating from callbacks to promises

The result parameter of the
fulfilled promise value is equivalent to the first parameter in
execute's callback. To update your code to use promises, change your code
as shown in the before and after examples below.