【问题标题】:Javascript rerun the function until condition is falseJavascript 重新运行函数,直到条件为假
【发布时间】:2021-11-18 15:02:30
【问题描述】:

通过 API,我想列出所有用户。每次每页最多只能有 100 个项目。所以我需要获取 next_page url 来重新运行函数 - runPages 来收集列表。所以条件是当next_page == null,然后会停止函数。

在我的代码中,我可以获得 next_page 网址。但是,它不会进一步运行。有人能找出问题所在吗?

const runPages = async (values) => {
  if (values.next_page != null) {
    for (const field of values.results) {
      row.appendChild(addCell(field.name));
      row.appendChild(addCell(field.email));
      tblbody.appendChild(row);
    }
    values = await checkPages(values.next_page); // get new values.data by url
    runPages(values);
  }
};
runPages(values);

const checkPages = async (value) => {
  return new Promise((resolve, reject) => {
    const getNewPageFromApi = async () => {
      const GetUrl = `${value}`;
      const Doorkey = { username: "XXX", password: "*****" };
      try {
        const response = await Axios.get(GetUrl, { auth: Doorkey });
        if (response.data.next_page != null) {
          resolve(response.data);
        }
      } catch (err) {
        reject("no more data");
      }
    };
    getNewPageFromApi();
  });
};

【问题讨论】:

    标签: javascript loops async-await


    【解决方案1】:

    我不知道这是否是您正在寻找的答案,但由于您在runPages 函数中检查values.next_page != null,您可以直接在Promise 中的@987654325 中调用resolve(response.data) @函数而不检查response.data.next_page != null

    【讨论】:

    • 谢谢@LHDi,是的,在我删除了条件之后——他们两个,现在我可以列出整个数据。非常感谢!
    • 没问题@MoonFactory
    猜你喜欢
    • 2017-12-03
    • 2018-01-19
    • 1970-01-01
    • 1970-01-01
    • 2021-06-10
    • 1970-01-01
    • 2012-01-10
    • 2018-03-17
    • 2017-07-21
    相关资源
    最近更新 更多