From the code sample and response provided, I am assuming the following:
- The javascript is running on the client side
- gapi calls are essentially asynchronous XMLHttpRequests
- .execute() methods take a callback function that will be invoked when the API call returns success or failure
I believe the issue lies with how you may be handling asynchronicity. gapi calls are made asynchronously so that other javascript on the client can continue executing while the network request is made. For instance In the following example, the second console.log() will most likely be invoked first as the api call make take time to return.
api.execute(function () {
console.log('API response');
});
console.log('Second invocation');
If the second console.log() must be invoked after the first console.log(), it must be placed within the callback function like so:
api.execute(function () {
console.log('API response');
console.log('Second invocation');
});
With this in mind, if you must have a few gapi calls happen sequentially, the calls must be made from within each callback. For example, to sequentially execute authenticate, uploadImage, saveUser, this would have to be written somewhat like this:
authenticate(currentUser).execute(function () {
// authenticatation is done, proceed
uploadImage(imageToSend).execute(function () {
// image was uploaded
saveUser(currentUser).execute(function () {
// user was saved
});
});
});
I hope this example is helpful for understanding the logic of asynchronous APIs and callbacks. For many gapi libraries, you may want to look at using
Promises to make this sort of logic somewhat clearer.