首页 > 解决方案 > 确保返回长度为5的递归函数

问题描述

我正在从 xml 源中获取一些数据,但我需要检查数组的长度(返回值)是否为 5,有时响应提供的数据少于 5 个元素(它是随机的)。

如果返回值 ( colorArray) 为 5,则 Promise 使用正确的数组解析。否则,如果函数重新运行,promise 将解析为undefined

感谢任何帮助理解为什么我在colorArray.length小于 5 时变得未定义,或者如果有人对我应该如何运行代码有任何更好的建议。

谢谢。

    const runAxios = async () => {
      console.log("function");
      const res = await axios.get("/api/palettes/random");

      let parser = new DOMParser();
      let xml = parser.parseFromString(res.data, "application/xml");

      let colors = xml.getElementsByTagName("hex");
      const colorArray = [];
      for (let i = 0; i < colors.length; i++) {
        let colorList = colors[i].firstChild.nodeValue;
        colorArray.push(colorList);
      }
      if (colorArray.length === 5) return colorArray;
      else runAxios();
    };

    const result = runAxios();

    result.then(e => {
      console.log(e);
    });

标签: javascript

解决方案


问题是您从未返回runAxios

    const runAxios = async () => {
      console.log("function");
      const res = await axios.get("/api/palettes/random");

      let parser = new DOMParser();
      let xml = parser.parseFromString(res.data, "application/xml");

      let colors = xml.getElementsByTagName("hex");
      const colorArray = [];
      for (let i = 0; i < colors.length; i++) {
        let colorList = colors[i].firstChild.nodeValue;
        colorArray.push(colorList);
      }
      if (colorArray.length === 5) return colorArray;
      else return runAxios(); // <----------------------------------This
    };

    const result = runAxios();

    result.then(e => {
      console.log(e);
    });

另外,根据您的要求,我建议使用 do-while 循环:

const runAxios = async () => {
      do {
          console.log("function");
          const res = await axios.get("/api/palettes/random");

          let parser = new DOMParser();
          let xml = parser.parseFromString(res.data, "application/xml");

          let colors = xml.getElementsByTagName("hex");
          const colorArray = [];
          for (let i = 0; i < colors.length; i++) {
            let colorList = colors[i].firstChild.nodeValue;
            colorArray.push(colorList);
          }
      } while(colorArray.length != 5);
      return colorArray;
    };

    const result = runAxios();

    result.then(e => {
      console.log(e);
    });

推荐阅读