【问题标题】:Triggering multiple webhook calls in a "Code by Zapier" action在“Zapier 代码”操作中触发多个 webhook 调用
【发布时间】:2021-08-01 23:03:27
【问题描述】:

我目前正在尝试在“Zapier 代码”操作中创建一个 for 循环。代码的意图是有一个执行 5 次的 for 循环;每次循环触发时,我都想点击一个 webhook。

for 循环执行完毕后,我使用回调函数输入一行代码以成功退出操作(不以回调函数结尾会触发错误“您必须返回单个对象或对象数组” )。

但是,如果我使用回调完成操作,则 webhook 永远不会被命中/触发(就好像 fetch 函数永远不会执行或无法完成一样)。如果我最后不使用回调(并使用类似“return output = {data: data};”之类的东西,我会收到“ReferenceError:未定义输出”错误,但会执行获取请求并且 webhook 被命中5次。

我使用的代码如下:

var url = "https://hooks.zapier.com/hooks/catch/5506184/byko7zw/";
var i;
for (i = 0; i < 5; i++) {
  var headers = {
    "Content-type": "application/json",
  };

  var body = JSON.stringify({ data: "Hello, World!", number: i });

  fetch(url, { method: "POST", headers: headers, body: body }).then((res) => {
      console.log(res);
    })
    .catch(callback);
}

callback(null, {});

有没有一种方法可以在 for 循环中成功地点击 webhook 指定的次数并成功退出,而不仅仅是一次或其他一次?任何帮助或建议将不胜感激!

【问题讨论】:

    标签: javascript fetch webhooks zapier


    【解决方案1】:

    是的,这是可能的!为请求使用await 来构建代码会更容易(而不是旧的callback 样式,虽然仍然有效,但相当混乱)。

    试试这样的:

    const url = "https://hooks.zapier.com/hooks/catch/5506184/byko7zw/";
    
    for (let number = 0; number < 5; number++) {
      var headers = {
        "Content-type": "application/json",
      };
    
      const body = JSON.stringify({ data: "Hello, World!", number });
    
      const response = await fetch(url, {
        method: "POST",
        headers,
        body,
      });
      response.throwForStatus(); // exit if there are errors
      // you can log the response here, but you don't need to
    }
    
    // code steps have to return _something_
    return { done: true };
    

    这将以更可预测的方式工作。您可能会遇到的一件事是,一个接一个地发出 5 个请求可能会很慢。如果确切的顺序无关紧要,您可以像这样并行化它们:

    const url = "https://hooks.zapier.com/hooks/catch/5506184/byko7zw/";
    
    var headers = {
      "Content-type": "application/json",
    };
    
    const numbers = [...Array(5).keys()]; // fancy way to get [0,1,2,3,4]
    const promiseArray = numbers.map((number) =>
      fetch(url, {
        method: "POST",
        headers,
        body: JSON.stringify({ data: "Hello, World!", number }),
      })
    );
    
    await Promise.all(promiseArray)
    
    // code steps have to return _something_
    return { done: true };
    

    【讨论】:

      【解决方案2】:

      快速说明:Zapier 文档指出,调用 response.throwForStatus(); 仅适用于核心 v9 或更早版本。 10+ 他们给你打电话。

      【讨论】:

      猜你喜欢
      • 2018-12-03
      • 2018-02-10
      • 2018-12-27
      • 2018-08-05
      • 2019-10-30
      • 2023-03-06
      • 2021-06-24
      • 2018-05-24
      • 2021-09-02
      相关资源
      最近更新 更多