Miguel
Miguel

Reputation: 109

How to wait for an HTTPrequest response

I have a function that request for an URL and if i use that function with a return in it the entire html code will be in the cell with the function name request "=testFormula()". Why if i use the formula function it will work but if i use the event one it will not work ?

function onEdit(event){
  testCom();
}
// This one will trigger automaticaly when you edit any cell in the sheet
function testCom(){
  var doc = SpreadsheetApp.getActiveSpreadsheet();
  doc.getRange('a1').setValue("Before fetching");
  var response = UrlFetchApp.fetch("http://www.google.com/");
  doc.getRange('a1').setValue(response);
}
// Use in a cell "=testFormula()" to run this function
function testFormula(){
 var response = UrlFetchApp.fetch("http://www.google.com/");
 return response;
}

Upvotes: 0

Views: 2715

Answers (2)

miturbe
miturbe

Reputation: 713

According to the documentation the fetch call is sequential, therefore the next line is not executed until the remote URL has been read

If you look at the example from the documentation, they do exactly what you are tyring to do, show the response in several cells:

var result = UrlFetchApp.fetch("http://api.twitter.com/1/statuses/user_timeline.json",
    options);
var o  = Utilities.jsonParse(result.getContentText());
var doc = SpreadsheetApp.getActiveSpreadsheet();
var cell = doc.getRange('a1');
var index = 0;
for (var i in o) {
     var row = o[i];
     var col = 0;
     for (var j in row) {
       if (fields[j]) {
         cell.offset(index, col).setValue(row[j]);
         col++;
       }
     }
     index++;
}

Upvotes: 0

Srik
Srik

Reputation: 7957

The onEdit() is a simple trigger and there are restrictions on what you can do inside simple triggers.

To overcome your problem, do the following
a. Rename your function to something else, say onEdit1()
b. In the script editor, click Resources --> Current project's triggers and add a new on edit trigger pointing to this function.

Authorize your script if needed and you should be good to go

Upvotes: 1

Related Questions