let parseCarList = [];
function addNewCars(req, res) {
parseRequestAndCreateCarList(req.body)
.then(function() {
if (parseCarList.length != 0) {
res.status(200).send('OK');
}
}, function (err) {
res.status(200).send(err);
});
}
function parseRequestAndCreateCarList(data) {
return carListParsing(data);
}
function carListParsing(data, parentId = null) {
//this function don't return anything
//It parse req.body and fill the parseCarList array
//I can't return anything because I use recursion
parseCarList.push({
car_company: data.car_company,
parent_id: parentId
});
if (data.daughters) {
data.daughters.forEach(item => {
carListParsing(item, data.car_company);
});
}
}
我的功能carListParsing是做數組:
[ { car_company: 'vw', parent_id: null },
{ car_company: 'seat', parent_id: 'vw' }]
但我想肯定的是,它的功能不會阻止我的代碼。
我得到錯誤「無法讀取屬性」,然後「未定義」。我的函數parseRequestAndCreateCarList返回它已經履行或沒有履行的承諾? 爲什麼在這種情況下'then'是未定義的?
P.S.有沒有辦法離開carListParsing沒有包裝parseRequestAndCreateCarList?
「這個函數不返回任何東西。它解析req.body並填充parseCarList數組。我不能返回任何東西,因爲我使用遞歸「如果它不返回任何內容,爲什麼你期望它返回一個承諾? – Cruiser
我的想法確切。你故意沒有返回任何東西,然後想知道爲什麼你不能在不存在的結果上調用函數? – Amy
「*我無法返回任何內容,因爲我使用遞歸*」沒有任何意義。特別是在遞歸的情況下,你總是需要'返回'一些東西。即使它只是遞歸調用的結果。 – Bergi