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 () {All fulfilled responses and rejected application errors passed to the handlers will have these fields:
gapi.client.plus.people.search({query: John}).then(function(res) {
console.log(res.result.items);
}, function(err) {
console.error(err.result);
});
})
{The promises can also be chained, making your code more readable:
result: *, // JSON-parsed body or boolean false if not JSON-parseable
body: string,
headers: (Object.),
status: (?number),
statusText: (?string)
}
gapi.client.youtube.playlistItems.list({Using promises makes it easy to handle results of API requests and offer elegant error propagation.
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);
});
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
0 comments:
Post a Comment