首页 > 解决方案 > 为什么我的异步函数返回 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];
     
    }

这是我得到的错误

在此处输入图像描述

我理解该消息的含义,但我不知道如何绕过它。

标签: javascriptecmascript-6

解决方案


Chrome 抱怨的原因是它试图将你的函数解构为变量。由于与 Array、Object 等函数不同的函数是不可迭代的,因此您收到了错误。

我发现您的代码存在两个主要问题。

  1. 你没有打电话给你的IFFE(私人范围)
  2. 您的 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];
 
}

推荐阅读