简体   繁体   English

如何在“Zapier 代码”中编写 fetch?

[英]How to write fetch in "Code by Zapier"?

In zapier I use an action of Code By Zapier .在 zapier 中,我使用了Code By Zapier的动作。 It's based on node.js.它基于 node.js。 I need to use fetch for implementing REST-API of my CRM.我需要使用fetch来实现我的 CRM 的 REST-API。

Here is the code I wrote, which runs well when I tried it with VS Code (outside Zapier):这是我编写的代码,当我使用 VS Code(在 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:我从 Zapier 得到的错误是:

If you are doing async (with fetch library) you need to use a callback!如果您正在执行异步(使用 fetch 库),则需要使用回调!

Please help me with solving it.请帮我解决它。

This is a classic mistake when coding in Node.js/callback environments. 在Node.js /回调环境中进行编码时,这是一个经典错误。

You are using console.log which prints to your console, but doesn't return data to the parent (Zapier in this case). 您正在使用console.log ,它会打印到您的控制台,但不会将数据返回给父节点(在这种情况下为Zapier)。

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! 我希望这有帮助!

These days, you can also use async/await , as noted by the default comment at the top of the sample code block:现在,您还可以使用async/await ,如示例代码块顶部的默认注释所示:

// this is wrapped in an `async` function
// you can use await throughout the function

const response = await fetch('http://worldclockapi.com/api/json/utc/now')
return await response.json()

See further examples in the docs: https://zapier.com/help/create/code-webhooks/javascript-code-examples-in-zaps#step-2查看文档中的更多示例: https : //zapier.com/help/create/code-webhooks/javascript-code-examples-in-zaps#step-2

Note that the free-tier has a 1 second timeout (especially relevant if you use Promise.all() to execute multiple fetches!)请注意,免费层有1 秒的超时时间(如果您使用Promise.all()执行多次获取,则尤其重要!)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM