Saving a response from a JavaScript JavaScript API request

Having tried the Google Javascript API on Google+, I ran into a problem.

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 one argument; callback function. However, I do not want to process the data immediately after receipt, I want to save it in the response variable specified at the beginning 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 was suggested that the callback function be as follows:

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

However, something interesting happens to the function. Here is the code I used for testing:

 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); 

Which console outputs are as follows:

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

The code appears to continue executing / before the callback function can be called. I need a way to verify this so that the code after the execute function is not called until the callback function is started.

+4
source share
1 answer
 request.execute(function(resp){ response = resp; afterExecute(); }); function afterExecute() { // this will not fire until after the response has been set. } 
+6
source

Source: https://habr.com/ru/post/1398737/


All Articles