I’m trying to make three different API calls in my Zapier code. I want to store the responses in variables and combine them later. Here’s what I’ve attempted:
const endpoints = ['endpoint1', 'endpoint2', 'endpoint3'];
let results = [];
for (let i = 0; i < endpoints.length; i++) {
results[i] = getData(endpoints[i]);
}
This is just a rough example. The problem is that results only contains empty objects {} instead of the actual API responses. How can I properly save the data from each request into the results array?
I’m new to working with async operations in Zapier, so any guidance on the correct approach would be super helpful. Thanks in advance!
The issue you’re encountering is common when dealing with asynchronous operations in Zapier. To properly store API responses, you need to handle promises correctly. Here’s an approach that should work:
const endpoints = ['endpoint1', 'endpoint2', 'endpoint3'];
let results = [];
for (const endpoint of endpoints) {
const response = await getData(endpoint);
results.push(response);
}
This uses a for…of loop with await, ensuring each API call completes before moving to the next. Remember to wrap this in an async function. Also, make sure your getData function is returning the actual API response data.
If you need to make the calls concurrently for efficiency, consider using Promise.all as suggested in the previous answer. Both methods are valid depending on your specific requirements.
hey there, i had similar probs with async stuff in zapier. try using async/await like this:
async function getAll() {
let results = [];
for (let endpoint of endpoints) {
let data = await getData(endpoint);
results.push(data);
}
return results;
}
this waits for each call to finish b4 moving on. hope it helps!
I ran into a similar issue when working with multiple API calls in Zapier. The problem you’re facing is likely due to the asynchronous nature of API requests. Here’s what worked for me:
Instead of using a regular for loop, try using Promise.all() with map(). This allows you to handle multiple async operations and wait for all of them to complete. Here’s an example:
This approach ensures that all API calls are made concurrently and the results are properly stored in the array. Make sure your getData() function returns a promise or is async.
Also, don’t forget to wrap your code in an async function if it’s not already. This way, you can use the await keyword.