问题描述
在使用Google+试用Google的Javascript API时,我遇到了一个障碍。
var response;
var request = gapi.client.request({
'path':'/ plus / v1 / people /'+THEUSERID,
'params':{}});
request.execute(function(resp){});
execute函数(gapi.client.HttpRequest.execute)一个回调函数。但是,我不希望在收到数据后立即处理数据,我想将它存储在代码开头声明的响应
变量中。有没有办法使用回调参数存储响应?
原谅我,如果这有一个明显的解决方案,我是一个新的JavaScript。
编辑:
有人建议回调函数如下:
request.execute(function(resp){response = resp;});
但是,这个函数很奇怪。这里是我用来测试的代码:
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);
控制台输出的内容如下:
回应:
undefined
GET https://www.googleapis.com/plus/v1/people/104815258973759324455?key=XXXXXXX
RESP:
({theactualjsondatathatIreceivedfromthecall})
显然,代码继续执行/ before /函数可以调用。我需要一个方法来检查这一点,所以在execute函数之后的代码不会被调用,直到回调函数运行。
pre> request.execute(function(resp){
response = resp;
afterExecute();
}
function afterExecute(){
//这将不会触发,直到响应已设置。
}
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.
request.execute(function(resp){
response = resp;
afterExecute();
});
function afterExecute() {
// this will not fire until after the response has been set.
}
这篇关于存储来自Google JavaScript API请求的响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!