繁体   English   中英

如何修复'TypeError:(images || [])。forEach不是一个函数'

[英]How to fix 'TypeError: (images || []).forEach is not a function'

在Node.js(正在使用MS Bot Framework)中,我试图遍历包含由fetch()返回的多个对象的数组。 它进行一次迭代,然后引发错误。

我确实已经从等式中删除了节点获取,并使用了对象的静态数组。 我也尝试转换为数组。 仍然是相同的结果: TypeError: (images || []).forEach is not a function在第一次迭代进行得很好之后TypeError: (images || []).forEach is not a function

这是当前的样子(缩短了对象值以提高可读性):

// exact copy of what fetch returns
let test = [
    {
        title: 'Power BI Desktop—Interactive Reports | Microsoft Power BI',
        link: 'https://support.office.com/',
        description: 'Create interactive reports with data',
        thumbnail: 'https://powerbi.microsoft.com/'
    }, {
        title: 'What is Power BI administration? - Power BI',
        link: 'https://support.office.com/',
        description: 'Learn about the configuration of Power BI ',
        thumbnail: 'https://docs.microsoft.com/'
    }, {
        title: 'Add a PowerBI tab to Teams',
        link: 'https://support.office.com/',
        description: 'You can add a new or existing PowerBI',
        thumbnail: 'https://support.office.com/'
    }
];

let cardContent = [];
test.forEach(element => {
    logger.debug('working on: %j', element);
    let card = CardFactory.heroCard(
        element.title,
        element.description,
        element.thumbnail,
        [element.link],
        ['Open Item']
    );
    cardContent.push(card);
});

仅供参考,这是我的提取功能的一部分:

return fetch(url + question)
    .then(res => res.json())
    .then(jsonResponse => {
        return jsonResponse;
    })

我真的不知道现在还能尝试什么。 完全相同的设置适用于我的应用程序的旧版-仅适用于axios但我也尝试过。

我运行您的代码,它可以正常工作-这意味着test数组不包含您认为包含的内容(可能包含fetch()返回的Promise)。 使用带有await关键字的fetch来获取响应,然后再次使用await来获取json(类似于下面的代码-我将其写在表格的头部)

async function load(url, question) {
    ...
    return await (await fetch(url + question)).json()
}

...
test = await load(url, question) // this call shoud be also inside async function

无法确定为什么(images || []).forEach在不知道images在哪里/如何定义的情况下不是一个函数,但是我要冒昧地猜测并说images 存在 ,并且是一个对象而不是数组。

尝试执行

const images = {};
images.forEach(image => console.log(image))

并且您将看到相同的结果, Uncaught TypeError: images.forEach is not a function

可能是要在其上运行forEach的对象中的images.data字段。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM