Search code examples
node.jscallbackfetchzapier

How to write fetch in "Code by Zapier"?


In zapier I use an action of Code By Zapier. It's based on node.js. I need to use fetch for implementing REST-API of my CRM.

Here is the code I wrote, which runs well when I tried it with VS Code (outside Zapier):

// the code by zapier includes already the require('fetch')

var api_token = "..."; // my api
var deal_name = "Example"; // a string

fetch("https://api.pipedrive.com/v1/deals/find?term="+deal_name+"&api_token=" + api_token)
  .then(function(res) {
    return res.json();
  }).then(function(json) {
     var deal_id = json.data[0].id;
     console.log("deal_id="+deal_id);
  }).catch(function(error) {
     console.log("error");
  });

output = {id: 1, hello: "world"}; // must include output...

The error I got from Zapier is:

If you are doing async (with fetch library) you need to use a callback!

Please help me with solving it.


Solution

  • This is a classic mistake when coding in Node.js/callback environments.

    You are using console.log which prints to your console, but doesn't return data to the parent (Zapier in this case).

    Here is an example of bad and good code:

    // bad code
    fetch(url)
      .then(function(res) {
        return res.json();
      }).then(function(json) {
        // when i run this in my node repl it works perfect!
        // the problem is this doesn't return the data to zapier
        // it just prints it to the system output
        console.log(json);
      });
    
    // good code
    fetch(url)
      .then(function(res) {
        return res.json();
      }).then(function(json) {
        // but if i swap this to callback, this works perfect in zapier
        callback(null, json);
      });
    

    I hope this helps!