Question

Run JavaScript return from promise

  • 29 October 2021
  • 2 replies
  • 549 views

Userlevel 1

Hi there Zapier community! 

 

I have an action that runs JavaScript to query multiple APIs and formulate an output. I am facing an issue figuring out how to return an output of the zap from a promise that is resolved. My zap ends with the following

 

Promise.all(results).then(result =>{
  output+= result.toString()
  return {"name": "CFP List", "body":output}
})

 

where output has the formatted output and results is an array of promise objects that my code waits for them to be resolved and aggregated. 

 

The issue with this approach however my Zap complains with the following

 

string: You did not define `output`! Try `output = {id: 1, hello: await Promise.resolve("world")};`

 

The output is formatted with the expected format the zap is looking for and i am not sure what the issue is.

 

Any pointers to this would be greatly appreciated. 

 

Here is the full code I have in my zap for reference

 

 

// Async function that queries an API and parses the results. Returns a promise.
async function getContent(category) {
  const baseURL = `https://<URL>?category=${category}`;

  let res = await fetch(baseURL).catch((err) => {
    throw new Error(`Error fetching content from ${baseURL}. ${err}`);
  });

  if (!res.ok) {
    throw new Error(`Response status from ${baseURL}: ${res.status}`);
  }

  let body = await res.json();
  
  let output = " ";
 

  body.items.map(item => {
    <business logic>

  })
  return output
}


let categories = ['cat1', 'cat2', 'cat3']

let output = " ";
let results = []
categories.map(cat => {

  // This returns a list of promises 
  results.push(getCFPs(cat))
})

// wait for all the promises to be resolved. The final result is in an object called output

Promise.all(results).then(result =>{
  output+= result.toString()
  return {"name": "CFP List", "body":output}
})

 

Cheers,

-Tamimi


This post has been closed for comments. Please create a new post if you need help or have a question about this topic.

2 replies

Userlevel 7
Badge +14

Hi @Solace 

Check the Code help docs: https://zapier.com/apps/code/help

Userlevel 1

Thanks @Troy Tessalone for the response! I referred to the examples section of that code however I wasn't able to find an example or references to using multiple fetches in the same zap. Do you have any example to that? 

 

My alternative right now is to have a fetch for every URL i a separate step which is not ideal