Zapier中的分页

时间:2019-09-29 16:48:15

标签: javascript zapier

我正在尝试遵循以下代码以从Zapier中的分页API获取所有记录。

const limitPerPage = 20;
const apiUrl = "https://myurl.com/data";
var lastCursor = null;
var output = null;

const getContent = async function (cursor) {
    let actualUrl = apiUrl + `?cursor=${cursor}&limit=${limitPerPage}`;
    var apiResults = await fetch(actualUrl)
        .then(resp => {
            return resp.json;
        });
}

const getEntireContentList = async function (cursor) {
    const results = await getContent(cursor);
    console.log("Retreiving data from API for cursor : " + cursor);
    if (results.metadata.cursor !== "") {
        return results.concat(await getEntireContentList(results.metadata.cursor));
    } else {
        return results;
    }
};


(async() => {
    const entireList = await getEntireContentList();
    console.log(entireList);
    output = entireList;
    callback(null, entireList);
})();

我得到错误 您尚未定义output!尝试output = {id: 1, hello: await Promise.resolve("world")};

我该如何解决?

1 个答案:

答案 0 :(得分:1)

您的问题是,尽管您正在await中使用该函数,但是在代码有机会运行之前,顶层继续执行并结束执行。

好消息是,Zapier已经将代码包装到一个异步函数中,因此您可以在顶层(按these docs使用)await

尝试以下方法:

const limitPerPage = 20;
const apiUrl = "https://myurl.com/data";
let lastCursor = null;
// var output = null; // zapier does this for you already

const getContent = async function (cursor) {
    const actualUrl = apiUrl + `?cursor=${cursor}&limit=${limitPerPage}`;
    const rawResponse = await fetch(actualUrl)
    return resp.json() // async function, you had it as a property
}

const getEntireContentList = async function (cursor) {
    const results = await getContent(cursor);
    console.log("Retreiving data from API for cursor : " + cursor);
    if (results.metadata.cursor !== "") {
        return results.concat(await getEntireUserList(results.metadata.cursor)); // should this be named getEntireContentList?
    } else {
        return results;
    }
};


return {
  results: await getEntireContentList()
}

我注意到这是一种递归方法。很好,但是请记住您的执行时间有限。您还可能会达到内存限制(取决于要返回的对象数),因此请注意这一点。