Получение "Uncaught TypeError: Невозможно прочитать свойство 'push' of undefined" спорадически - PullRequest
0 голосов
/ 05 декабря 2018

Я пытаюсь получить данные из URL-адреса и добавить их в массив, затем выполнить цикл внутри помещенных данных и снова вызвать URL-адрес и передать извлеченные данные в свойство «data» элемента массива (и т. Д.и так далее).Это работает большую часть времени, но иногда я получаю сообщение об ошибке, что «Невозможно прочитать свойство« push »из неопределенного случайным образом в« seconddelement.data.push »или« thirdelement.data.push »или« fourthelement.data.push ».пытаясь выяснить, что это за ошибка, но она очень часто дает сбой. Любая помощь в том, что может быть проблема?

firstHeadingArray = []
request.get(config.url.sectionMaster + "?parentSectionCode=" + sectionCode, function (err1, firstresult) {
        if (err1) { return next(err1) }
        if (firstresult != undefined) {
            // console.log("---------------------------FIRST------------------------")
            // console.log(JSON.parse(firstresult.body))
            firstresult = JSON.parse(firstresult.body).data
            if (firstresult != null) {
                firstresult.forEach(function (firstelement) {
                    firstHeadingArray.push({
                        "entityId": entityId,
                        "finYear": finYear,
                        "sectionCodeHead": sectionCode,
                        "unit": unit,
                        "sectionCodeDet": firstelement.sectionCode,
                        "sectionName": firstelement.sectionName,
                        "asOfDate": "",
                        "childAmount": "0.00",
                        "parentAmount": "0.00",
                        "manualEntry": 0,
                        "dispOrder": firstelement.dispOrder,
                        "AppStatus": "",
                        "Status": "",
                        "WF_SERIALNUMBER": "",
                        "WF_ACTION": "",
                        "leafNode": "",
                        "data": []
                    })
                })
                async.forEachSeries(firstHeadingArray, function (secondelement, scallback) {
                    // console.log(secondelement.sectionCodeDet)
                    request.get(config.url.sectionMaster + "?parentSectionCode=" + secondelement.sectionCodeDet, function (srerr, secondresult) {
                        if (srerr) { return next(srerr) }
                        // console.log("-----------------------------------SECOND--------------------------------")
                        // console.log(JSON.parse(secondresult.body))
                        if (secondresult != undefined) {
                            // console.log(secondresult)
                            secondresult = JSON.parse(secondresult.body).data
                            if (secondresult != null) {
                                secondresult.forEach(function (secelement) {
                                    secondelement.data.push({
                                        "entityId": entityId,
                                        "finYear": finYear,
                                        "sectionCodeHead": sectionCode,
                                        "unit": unit,
                                        "sectionCodeDet": secelement.sectionCode,
                                        "sectionName": secelement.sectionName,
                                        "asOfDate": "",
                                        "childAmount": "0.00",
                                        "parentAmount": "0.00",
                                        "manualEntry": 0,
                                        "dispOrder": secelement.dispOrder,
                                        "AppStatus": "",
                                        "Status": "",
                                        "WF_SERIALNUMBER": "",
                                        "WF_ACTION": "",
                                        "leafNode": "",
                                        "data": []
                                    })
                                })

                                // console.log(secondelement)
                                async.forEachSeries(secondelement.data, function (thirdelement, tcallback) {
                                    // console.log("here")
                                    // console.log(thirdelement.sectionCodeDet)
                                    request.get(config.url.sectionMaster + "?parentSectionCode=" + thirdelement.sectionCodeDet, function (trerr, thirdresult) {
                                        // console.log("-----------------------------------------THIRD--------------------------------------")
                                        // console.log(JSON.parse(thirdresult.body))
                                        if (trerr) { return next(trerr) }
                                        if (thirdresult != undefined) {
                                            thirdresult = JSON.parse(thirdresult.body).data
                                            if (thirdresult != null) {
                                                thirdresult.forEach(function (telement) {
                                                    thirdelement.data.push({
                                                        "entityId": entityId,
                                                        "finYear": finYear,
                                                        "sectionCodeHead": sectionCode,
                                                        "unit": unit,
                                                        "sectionCodeDet": telement.sectionCode,
                                                        "sectionName": telement.sectionName,
                                                        "asOfDate": "",
                                                        "childAmount": "0.00",
                                                        "parentAmount": "0.00",
                                                        "manualEntry": 0,
                                                        "dispOrder": telement.dispOrder,
                                                        "AppStatus": "",
                                                        "Status": "",
                                                        "WF_SERIALNUMBER": "",
                                                        "WF_ACTION": "",
                                                        "leafNode": "",
                                                        "data": []
                                                    })
                                                })
                                                // console.log(thirdresult)
                                                async.forEachSeries(thirdelement.data, function (fourthelement, fcallback) {
                                                    // console.log(fourthelement.sectionCodeDet)
                                                    request.get(config.url.sectionMaster + "?parentSectionCode=" + fourthelement.sectionCodeDet, function (frerr, fourthresult) {
                                                        // console.log("------------------------FOURTH---------------------")
                                                        // console.log(JSON.parse(fourthresult.body))
                                                        if (frerr) { return next(frerr) }
                                                        if (fourthresult != undefined) {
                                                            fourthresult = JSON.parse(fourthresult.body).data
                                                            if (fourthresult != null) {
                                                                fourthresult.forEach(function (felement) {
                                                                    fourthelement.data.push({
                                                                        "entityId": entityId,
                                                                        "finYear": finYear,
                                                                        "sectionCodeHead": sectionCode,
                                                                        "unit": unit,
                                                                        "sectionCodeDet": felement.sectionCode,
                                                                        "sectionName": felement.sectionName,
                                                                        "asOfDate": "",
                                                                        "childAmount": "0.00",
                                                                        "parentAmount": "0.00",
                                                                        "manualEntry": 0,
                                                                        "dispOrder": felement.dispOrder,
                                                                        "AppStatus": "",
                                                                        "Status": "",
                                                                        "WF_SERIALNUMBER": "",
                                                                        "WF_ACTION": "",
                                                                        "leafNode": "",
                                                                        "data": []
                                                                    })
                                                                })
                                                            }
                                                            fcallback()
                                                        } else {
                                                            res.send({ message: "Something went wrong, please try again." })
                                                            return;
                                                        }
                                                    })
                                                }, function (ferr) {
                                                    // console.log("finished1")
                                                    if (ferr) { return next(ferr) }
                                                    tcallback()
                                                })
                                            } else { tcallback() }

                                        } else {
                                            res.send({ message: "Something went wrong, please try again." })
                                            return;
                                        }
                                    })
                                }, function (terr) {
                                    // console.log("finished2")
                                    if (terr) { return next(terr) }
                                    scallback()
                                })
                            } else { scallback() }
                        } else {
                            res.send({ message: "Something went wrong, please try again." })
                            return;
                        }
                    })
                },function(err){
                 res.send(firstHeadingArray)
}

Ответы [ 2 ]

0 голосов
/ 05 декабря 2018

Причина вашей проблемы в том, что данные не являются массивом, поэтому они не содержат метод push в данных.

Проверьте в этом случае, получили ли вы seconddelement.data, thirdelement.dataкак массив или нет, если не делать то, что вы когда-либо хотите, сделать его массивом или не выдвигать.

Проверьте, является ли значение массивом.

Новый подход

Array.isArray(obj)

старый подход

Object.prototype.toString.call(obj) === '[object Array]';
0 голосов
/ 05 декабря 2018

Вы получили ошибку Getting “Uncaught TypeError: Cannot read property 'push' of undefined” sporadically из-за того, что data равен undefined или не Array

До push данных в array просто проверьте их exists иArray.

if (secondelement.data && Array.isArray(secondelement.data)) {
  secondelement.data.push({
    "entityId": entityId,
    "finYear": finYear,
    "sectionCodeHead": sectionCode,
    "unit": unit,
    "sectionCodeDet": secelement.sectionCode,
    "sectionName": secelement.sectionName,
    "asOfDate": "",
    "childAmount": "0.00",
    "parentAmount": "0.00",
    "manualEntry": 0,
    "dispOrder": secelement.dispOrder,
    "AppStatus": "",
    "Status": "",
    "WF_SERIALNUMBER": "",
    "WF_ACTION": "",
    "leafNode": "",
    "data": []
  })
}

Проверьте то же самое для thirdelement.data и fourthelement.data

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...