javascript - 确保返回长度为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);
});
解决方案
问题是您从未返回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);
});
推荐阅读
- c# - 如何将 DateTime 字节的二进制反序列化配置为 DateTimeOffset?
- sql - SQL - 根据其他两列的值创建一个数组
- python - 在 Python 中使用多处理时没有得到预期的结果
- c# - 在 MVC 解决方案中访问 Web 表单页面文本框控件
- c++ - 多线程矩阵乘法 C++
- sql - Oracle 包含对包含“非”字的短语的工作失败
- java - 使用 compareTo() 对电子邮件地址进行排序返回意外结果
- python - GPFlow:如何解释平均模型的不确定性
- php - 图像已插入但未保存在服务器上
- python-3.x - ElementNotInteractable 异常:消息:元素无法滚动到视图中