javascript - 为什么我的异步函数返回 Uncaught TypeError: (intermediate value) is not iterable
问题描述
我试图从异步函数中检索一些数据但没有成功,这里是代码:
links(originalArray = "/views/layouts/footer-links.json"){
let [template, dataset] = async function () {
let html = null,
// Get the post data
response = await fetch(originalArray),
dataset = await response.json(),
template = dataset.footerLinks.map(header=>{
const html = `
<div class="cell medium-3">
<h4 title="${header.type}">${header.text}</h4>
<ul class="menu vertical">
${header.anchors.map(link=>`
<li> ${link.label} </li>
`).join("")}
</ul>
</div>
`;
return html;
}).join(""); ;
return html = {
template: template,
dataset: dataset
};
};
console.log(("In getDataset:::. ",[template, dataset]));
return [template, dataset];
}
这是我得到的错误
我理解该消息的含义,但我不知道如何绕过它。
解决方案
Chrome 抱怨的原因是它试图将你的函数解构为变量。由于与 Array、Object 等函数不同的函数是不可迭代的,因此您收到了错误。
我发现您的代码存在两个主要问题。
- 你没有打电话给你的IFFE(私人范围)
- 您的 IFFE 返回一个对象,但是您正在解构 [ template, dataset ] 作为预期的数组。
async links(originalArray = "/views/layouts/footer-links.json"){
let { template, dataset } = await (async function () { // you have to await your async IFFE since "async" returns promises and "await" awaits and resolves promises
let html = null,
// Get the post data
response = await fetch(originalArray),
dataset = (await response).json(), // I fixed this part for you. You have to await response and then call .json() since response is a Promise not an Object without "await"
template = dataset.footerLinks.map(header => {
const html = `
<div class="cell medium-3">
<h4 title="${header.type}">${header.text}</h4>
<ul class="menu vertical">
${header.anchors.map(link=>`
<li> ${link.label} </li>
`).join("")}
</ul>
</div>
`;
return html;
}).join("");
return {
template, // you don't need "template: template"
dataset
};
})(); // call the IFFE
console.log(("In getDataset:::. ",[template, dataset]));
return [template, dataset];
}
推荐阅读
- post - Python:运行带有错误消息的 POST 请求
- sql - 如何(取消)将多个指标转换为单个列?
- python - 'Pyqt5' 和 'multiprocessing' 不绘制图形
- javascript - 编辑一组相互触发的组合框
- r - 如何根据 Excel 电子表格中重复标题的值在 R 中创建新列?
- advanced-custom-fields - 带有 ACF 的 Elementor 中的条件文本
- macos - 查找在 OSX 上找不到的 util
- sql - 在不使用文字的情况下向时间戳添加间隔
- rest - 使用 C# REST API 从 TFS 获取用户身份
- r - R错误:替换长度为零 - 需要帮助