I have a array of strings.
let’s say
My problem statement is Iterate over each value of this array and call api call and write response of each data in google sheet simultaneously.
let input_data=["value1","value2",...... , "value30"]
var mySheet = SpreadsheetApp.openById('YOUR_SHEET_ID').getActiveSheet();
for (let [idx, each] of input_data.entries()) {
// this is a Asynchronous function is basically take input and get response from api using UrlFetchApp and write in google sheet row
InsertApiResponseIntoCell(each,mySheet)
}
So requirement is whichever gets first response from server will written in google sheet.
But problem is each api call pauses the task and wait for complete , so technically not behaving Asynchronous. After all operation all the datas are written in cells
How can i get response from api call and write it in cell rows while iterating over loop?
I have tried this one
for more context
async function insertApiResponseIntoCell(input, sheet) {
var apiUrl = 'YOUR_API_URL_HERE'; // Replace with the actual API URL
var response = UrlFetchApp.fetch(apiUrl);
var responseBody = response.getContentText();
// Parse the response and extract the data you need
var responseData = JSON.parse(responseBody);
var lastRow = sheet.getLastRow() + 1;
var targetRange = sheet.getRange(lastRow, 1, 1, responseData.length);
// Write the response data to the target range
targetRange.setValues([[responseData]]);
}
2
Answers
Sheet0:
It looks like you’re dealing with an asynchronous behavior in your loop due to the API calls. Since UrlFetchApp.fetch is synchronous and blocks the execution until it gets a response, you won’t achieve true parallel asynchronous behavior with this approach.
However, you can achieve a sort of concurrency by using UrlFetchApp.fetchAll method, which allows you to make multiple API requests concurrently. Here’s how you can modify your code to use it:
Please note:
insertApiResponseIntoCell returns a Promise after fetching the API response.
We’re using .map to create an array of promises, each representing an API call.
Promise.all waits for all promises to resolve before logging a message.
This approach doesn’t guarantee exact parallel execution, but it does enable concurrent API requests, which should help speed up the process.