使用autoCompletejs从后端获取keys时遇迭代非可迭代实例类型错误
问题解决:autoComplete.js 非可迭代实例错误
错误根源
你配置的keys字段直接赋值了fetch返回的Promise对象,而非实际的数组。autoComplete.js会尝试迭代keys来匹配搜索内容,但Promise本身不具备可迭代性,因此抛出TypeError: Invalid attempt to iterate non-iterable instance错误。
解决方案
方案1:先获取keys再初始化autoComplete
先异步获取keys数组,再用这个数组初始化autoComplete,确保keys是实际可迭代的数组:
(async function() { // 先获取keys数组 const keysRes = await fetch("/keys"); const keys = await keysRes.json(); // 初始化autoComplete const autoCompleteJS = new autoComplete({ selector: "#autoComplete", placeHolder: "搜索供应商...", data: { src: async () => { try { document.getElementById("autoComplete").setAttribute("placeholder", "Loading..."); const source = await fetch("/suppliers"); const data = await source.json(); document.getElementById("autoComplete").setAttribute("placeholder", autoCompleteJS.placeHolder); return data; } catch (error) { return []; // 出错时返回空数组避免异常 } }, keys: keys, cache: true }, // 其他配置项 }); })();
方案2:将keys改为异步函数(需确认autoComplete版本支持)
部分新版本的autoComplete.js支持keys为异步函数,可直接返回获取到的数组:
data: { src: async () => { try { document.getElementById("autoComplete").setAttribute("placeholder", "Loading..."); const source = await fetch("/suppliers"); const data = await source.json(); document.getElementById("autoComplete").setAttribute("placeholder", autoCompleteJS.placeHolder); return data; } catch (error) { return []; } }, keys: async () => { const res = await fetch("/keys"); return res.json(); }, cache: true },
额外注意点
你的src返回的数据结构是一个包含单个对象的数组,该对象的键是供应商编号,值是供应商名称。如果希望autoComplete搜索供应商名称,当前的keys配置(编号数组)会让插件尝试匹配对象中对应编号键的值,这是符合预期的;如果需要调整搜索逻辑,可以修改后端返回的数据结构,比如将每个供应商改为{ id: 'xxx', name: 'xxx' }的格式,再把keys设为['name']。
内容的提问来源于stack exchange,提问作者rdweb
相关产品推荐
相关产品推荐

