问题
A google gapi.client.load for a google api can return a promise as discussed here. However, if you wish to use the javascript client for your own app engine component using cloud endpoints, the gapi.client.load has a different method signature, as shown in this angular post:
gapi.client.load('guestbook', 'v1', function() {
$scope.is_backend_ready = true;
$scope.list();
}, '/_ah/api');
Here, there is a fourth parameter and it is not the success function. So I'm not sure how a promise can be used.
回答1:
Investigating this further, it seems that if you send "undefined" as the 3rd praameter, then you can use this call as a promise, like:
gapi.client.load('guestbook', 'v1', undefined, '/_ah/api').then(function() {
$scope.is_backend_ready = true;
$scope.list();
});
I haven't seen any google documentation of this. Please let me know if this exists.
回答2:
If the goal is just to perform some action after the client is loaded you could simply check for an error in the callback function. This will work with or without the client.init function. Something like this:
gapi.client.init({}).then(() => {
gapi.client.load('some-api', "v1", (err) => { callback(err) }, "https://someapi.appspot.com/_ah/api");
}, err, err);
function callback(loadErr) {
if (loadErr) { err(loadErr); return; }
// success code here
}
function err(err){
console.log('Error: ', err);
// fail code here
}
Example
If you really need a promise returned you can simply wrap this code in a function and return a promise in the callback function above.
回答3:
"Cloud Endpoints client library does not support the Promise API of AngularJS for describing this kind of asynchronous processing."
You can find this stated in https://cloud.google.com/solutions/angularjs-cloud-endpoints-recipe-for-building-modern-web-applications .
To get around this is to write (or better generate) thin wrapper by converting all callbacks to promises
as explained in https://riztaak.wordpress.com/2015/04/05/promises-promises-using-google-cloud-endpoint-in-angularjs/
来源:https://stackoverflow.com/questions/28901570/can-gapi-client-load-for-cloud-endpoints-return-a-promise