Promises in the Google APIs JavaScript Client Library

OCT 02, 2014
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 gapi.client.plus.people.search 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 () {
      gapi.client.plus.people.search({query: ‘John’}).then(function(res) {
      console.log(res.result.items);
      }, function(err) {
      console.error(err.result);
      });
      })
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:
gapi.client.youtube.playlistItems.list({
      playlistId: 'PLOU2XLYxmsIIwGK7v7jg3gQvIAWJzdat_',
      part: 'snippet'
      }).then(function(res) {
      return res.result.items.map(function(item) {
      return item.snippet.resourceId.videoId;
      });
      }).then(function(videoIds) {
      return gapi.client.youtube.videos.list({
      id: videoIds.join(','),
      part: 'snippet,contentDetails'
      });
      }).then(function(res) {
      res.result.items.forEach(function(item) {
      console.log(item);
      });
      }, function(err) {
      console.error(error.result);
      });
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