Storing a Response From a Google JavaScript API Request

狂风中的少年 提交于 2019-12-06 04:50:52

问题


While trying out Google's Javascript API with Google+, I ran across a snag.

var response;
var request = gapi.client.request({
    'path': '/plus/v1/people/' + "THEUSERID", 
    'params': {}});
request.execute(function(resp){});

The execute function (gapi.client.HttpRequest.execute) takes a single argument; a callback function. However, I do not wish to handle the data immediately after I receive it, I want to store it in the response variable I declared at the start of the code. Is there a way to use the callback argument to store the response?

Forgive me if this has an obvious solution, I'm a little new to JavaScript.

EDIT: It has been suggested that the callback function be as follows:

request.execute(function(resp){response = resp;});

However, something curious happens with the function. Here is the code I used to test:

var response;
var request = gapi.client.request({
    'path': '/plus/v1/people/' + userID,
    'params': {}});
request.execute(function(resp){
    console.log("RESP:");
    console.log(resp);
    response = resp;});
console.log("RESPONSE:");
console.log(response);

What the console outputs is as follows:

RESPONSE:
undefined
GET https://www.googleapis.com/plus/v1/people/104815258973759324455?key=XXXXXXX
RESP:
({theactualjsondatathatIreceivedfromthecall})

Apparently, the code continues executing /before/ the execute callback function can be called. I need a way to check for this, so that the code after the execute function is not called until the callback function is run.


回答1:


request.execute(function(resp){
  response = resp;
  afterExecute();
});
function afterExecute() {
  // this will not fire until after the response has been set.
}


来源:https://stackoverflow.com/questions/9475324/storing-a-response-from-a-google-javascript-api-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!