首页 > 解决方案 > 无法读取“for...of”循环中的第一次迭代/迭代为空

问题描述

我有一个数组 questionsArray,我需要在该数组中的每个问题中做一些事情。第一次迭代有效,但除此之外它说它无法读取 null 的属性 x。这是为什么?- 这是遍历数组的代码:

var insertion = new Promise(async (resolve, reject) => {
                    for(const question of questionsArray){
                        await db.query('INSERT INTO `ml-questions-data` (`text`, `status`, `question_id`, `answer_text`, `answer_status`, `answer_date`, `item_id`, `seller_id`, `created`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);',
                         [question.text, question.status, question.id, question.answer.text, question.answer.status, question.answer.date_created, question.item_id, question.seller_id, question.date_created], (erro)=>{
                            if(erro){
                                reject(erro)
                            }
                            else{
                                console.log('array iteration! db insertion')
                            }
                        })
                    }
                    resolve()
                });

- 这是 questionsArray 数据:

[
    {
        "date_created": "2019-09-30T03:18:08.000-04:00",
        "item_id": "MLB1329418290",
        "seller_id": 158369990,
        "status": "ANSWERED",
        "text": "olá, gostaria de entender como funciona isso?",
        "id": 6553335409,
        "deleted_from_listing": false,
        "hold": false,
        "answer": {
            "text": "pois bem, vamos adicionar um texto de resposta no json",
            "status": "ACTIVE",
            "date_created": "2019-09-30T03:24:52.120-04:00"
        },
        "from": {
            "id": 444188609,
            "answered_questions": 2
        }
    },
    {
        "date_created": "2019-09-30T03:22:21.000-04:00",
        "item_id": "MLB1329418290",
        "seller_id": 158369990,
        "status": "BANNED",
        "text": "<p style=\"display: inline-block;font-family:Helvetica,Arial,'sans-serif';font-size:13px;line-height:17px;background: url('http://static.mlstatic.com/org-img/ch/ui/0.10.7/assets/icons.png') no-repeat;border-radius: 3px;border-style: solid;border-width: 1px;margin: 0 0 5px;padding: 8px 10px 8px 34px;text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5);background-color: #FCF8CB;background-position: -225px -101px;border-color: #E4E2B8;\">Tivemos que excluir esta pergunta porque não está de acordo com as nossas <a href=\"https://www.mercadolivre.com.br/ajuda/politicas-para-cadastramento-de-produtos_1002\">Políticas para Cadastramento de Anúncios</a>.</p>",
        "id": 6553335807,
        "deleted_from_listing": false,
        "hold": false,
        "answer": null,
        "from": {
            "id": 444188609,
            "answered_questions": 2
        }
    },

    the array goes on.....
]

这是错误节点提示:

C:\ServidorMaster\Alura\ProjetosNODE\project2>node server
server rodando na porta 3010
Conexão com banco de dados mySQL estabelecida
**(node:9360) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'text' of null
    at Promise (C:\ServidorMaster\Alura\ProjetosNODE\project2\src\app\modelos\DAOs\mercado-livre\ml-DAO.js:205:88)**
(node:9360) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:9360) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
**array iteration! db insertion**

所以它说无法读取属性,但是第一次迭代,一个对象,成功地插入到我的数据库中。有人可以帮我理解这里发生了什么吗?

标签: javascriptnode.jsfor-loop

解决方案


“answer”在数组的第二个元素中为空,因此您无法访问 question.answer.text。(在数组的第一个元素中,answer 是一个带有名为“text”的元素的地图)。

对于插入尝试访问其成员的所有部分,您将需要处理输入数组中 answer 为 null 的情况。


推荐阅读