【问题标题】:How to write fetch in "Code by Zapier"?如何在“Zapier 的代码”中编写 fetch?
【发布时间】:2015-11-10 13:47:27
【问题描述】:

在 zapier 中,我使用Code By Zapier 的操作。它基于 node.js。 我需要使用 fetch 来实现我的 CRM 的 REST-API。

这是我编写的代码,当我使用 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...

我从 Zapier 得到的错误是:

如果您正在执行异步操作(使用 fetch 库),您需要使用 回调!

请帮我解决。

【问题讨论】:

    标签: node.js callback fetch zapier


    【解决方案1】:

    这是在 Node.js/callback 环境中编码时的典型错误。

    您正在使用console.log,它会打印到您的控制台,但不会将数据返回给父级(在本例中为 Zapier)。

    下面是一个坏代码和好代码的例子:

    // 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);
      });
    

    我希望这会有所帮助!

    【讨论】:

    • 您好,我可以在一个 zap 中创建多个 fetchs 语句吗?谢谢。
    • @hungndv,我明白这个机制是如何工作的。您可以在 fetch 中编写 fetch。您总是需要通过回调完成程序。因此,您不能在 fetch 之后编写 fetch!因为回调将终止 ZAP 动作。但是,Bryan 最近为一个触发器启用了几个操作,这些操作是一个一个完成的,因此您可以逐个执行代码两次,并且您可能会成功过滤或更改第二个代码作为第一个代码的结果,但我没有尝试还没有。
    【解决方案2】:

    现在,您还可以使用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()
    

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

    请注意,免费层有 1 秒超时(如果您使用 Promise.all() 执行多次提取尤其重要!)

    【讨论】:

      猜你喜欢
      • 2017-01-03
      • 2015-11-10
      • 1970-01-01
      • 2020-08-24
      • 2018-05-01
      • 2021-06-25
      • 2016-12-02
      • 1970-01-01
      • 2016-03-08
      相关资源
      最近更新 更多