簡體   English   中英

如何在“Zapier 代碼”中編寫 fetch?

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

在 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 /回調環境中進行編碼時,這是一個經典錯誤。

您正在使用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);
  });

我希望這有幫助!

現在,您還可以使用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()執行多次獲取,則尤其重要!)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM