I'm writing a script that queries an API multiple times based on an ID. The odd part is when I just log the ID, the script seems to run fine. When I try to loop through the response from the API, it only happens once.
Here's what I'm working with
// Makes the request by ID
function requestById() {
var ids = sheet.getRange(2,1,sheet.getLastRow() - 1).getValues()
for (i = 0; i < ids.length; i ) {
submitById(ids[i][0])
}
}
// Fetches the results from the API
function submitById(x) {
var url = {api URL} x
const options = {
contentType: "application/json",
headers: { Authorization: "Basic " b64apiKey, 'Content-Type': 'application/json'},
}
var res = JSON.parse(UrlFetchApp.fetch(url, options))
Logger.log(x)
for (i = 0; i < res.tasks[0].result[0].items.length; i ) {
Logger.log(res.tasks[0].result[0].items[i])
}
The really weird part is that if I just log the IDs in the second function, it shows that the first loop in requestById() runs the appropriate amount of times. If I run a loop on the result in the second function... it only runs for the first ID and none of the others.
I'm not sure why it's not working only when I run a loop on the result. I use a similar format elsewhere in my project and it works fine
How do I get this to run for every ID?
PS. I have an API key and {api URL} in my code is an actual URL. These are just placeholders for this question. Similarly, sheet is defined elsewhere
CodePudding user response:
If you are actually using your showing script, when I saw your showing script, i
is used with for (i = 0; i < ids.length; i ) {,,,}
in the function requestById()
. And, i
of for (i = 0; i < res.tasks[0].result[0].items.length; i ) {
is also used in the function submitById(x)
as i = 0
. I'm worried that this might be the reason for your current issue. In the case of i = 0
, the i
in the function requestById()
might be used. By this, the index of the loop might not be able to be correctly run. In order to avoid this, how about the following modification?
Modified script:
From:
for (i = 0; i < res.tasks[0].result[0].items.length; i ) {
Logger.log(res.tasks[0].result[0].items[i])
}
To:
for (var i = 0; i < res.tasks[0].result[0].items.length; i ) {
Logger.log(res.tasks[0].result[0].items[i])
}
or
for (var j = 0; j < res.tasks[0].result[0].items.length; j ) {
Logger.log(res.tasks[0].result[0].items[j])
}
Note:
- But, I have no information about
ids.length
andres.tasks[0].result[0].items.length
. So, if this modification was not useful, can you provide the values of them?