Promises in the Google APIs JavaScript Client Library

October 02, 2014

Link copied to clipboard
The JavaScript Client Library for Google APIs is now Promises/A+-conformant. Requests made using gapi.client.request, gapi.client.newBatch, and from generated API methods like are also promises. You can pass in response and error handlers through their then methods.

Requests can be made using the then syntax provided by Promises:
gapi.client.load(‘plus’, ‘v1’).then(function () {{query: ‘John’}).then(function(res) {
  }, function(err) {
All fulfilled responses and rejected application errors passed to the handlers will have these fields:
  result: *, // JSON-parsed body or boolean false if not JSON-parseable
  body: string,
  headers: (Object.),
  status: (?number),
  statusText: (?string)
The promises can also be chained, making your code more readable:{
      playlistId: 'PLOU2XLYxmsIIwGK7v7jg3gQvIAWJzdat_',
      part: 'snippet'
    }).then(function(res) {
      return {
        return item.snippet.resourceId.videoId;
    }).then(function(videoIds) {
        id: videoIds.join(','),
        part: 'snippet,contentDetails'
    }).then(function(res) {
      res.result.items.forEach(function(item) {
    }, function(err) {
Using promises makes it easy to handle results of API requests and offer elegant error propagation.

To learn more about promises in the library and about converting from callbacks to promises, visit Using Promises and check out our latest API reference.

Posted by Jane Park, Software Engineer