October 02, 2014
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.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.The promises can also be chained, making your code more readable:), status: (?number), statusText: (?string) }
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.