简体   繁体   English

在zapier的代码中使用循环中的fetch

[英]Using fetch in a loop in code by zapier

I want to do 3 different api call from my zapier code, get their returns in variables and merge them. 我想从我的zapier代码中做3个不同的api调用,在变量中获取它们并合并它们。 I can't figure out how to do that. 我无法弄清楚如何做到这一点。 It will be like: 它会像:

var urls = [apiUrl1, apiUrl2, apiUrl3];
var output = [];

for ( i = 0; i < urls.length; i++ ) {
    output[i] = fetch( urls[i] );
}

This is an example code. 这是一个示例代码。 I can't get response to output, it gets only a blank object {}. 我无法获得对输出的响应,它只获得一个空白对象{}。 What will be the procedure to save the fetch return values in the output array? 在输出数组中保存获取返回值的过程是什么?

Since apparently the folks at Zapier do not like to give out working examples or any sort of decent documentation for this level of code intricacy... here is a working example: 很明显,Zapier的人们不喜欢为这个级别的代码复杂性提供工作示例或任何类型的文档......这是一个工作示例:

var promises = [];

for (var i = urls.length - 1; i >= 0; i--) {
    promises.push(fetch(urls[i]));
}

Promise.all(promises).then(function(res){
    var blobPromises = [];
    for (var i = res.length - 1; i >= 0; i--) {
        blobPromises.push(res[i].text());
    }
    return Promise.all(blobPromises);
}).then(function(body){
    var output = {id: 1234, rawData: body};
    callback(null, output);
}).catch(callback);

This may not be the cleanest solution, but it works for me. 这可能不是最干净的解决方案,但它对我有用。 Cheers! 干杯!

Two things you'll need to brush up on: 你需要注意两件事:

  1. Promises - especially Promise.all() - there is lots out there about that. 承诺 - 特别是Promise.all() - 有很多关于那个。
  2. Callback to return the data asynchronously. 回调以异步方式返回数据。 Our help docs describe this. 我们的帮助文档描述了这一点。

The main reason your code fails is because you are assuming the fetch happens immediately. 您的代码失败的主要原因是您假设提取立即发生。 In JavaScript that is not the case - it happens Async and you have to use promises and callbacks to wait until they are done before returning the output via the callback! 在JavaScript不是这种情况下 - 它发生Async,你必须使用promises和callbacks等待它们完成后再通过回调返回输出!

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

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