【发布时间】:2017-06-15 11:30:20
【问题描述】:
代码:
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' }]
但我想确定,它的功能不会阻塞我的代码。
我收到错误“无法读取未定义的属性 'then'”。我的函数 parseRequestAndCreateCarList 是否返回已实现的承诺? 为什么在这种情况下“then”是未定义的?
附:有没有办法在没有包装器 parseRequestAndCreateCarList 的情况下离开 carListParsing?
【问题讨论】:
-
"这个函数不返回任何东西。它解析 req.body 并填充 parseCarList 数组。我不能返回任何东西,因为我使用递归"如果它不返回任何东西,你为什么期望它返回一个承诺?
-
我的想法完全正确。您故意不返回任何内容,然后想知道为什么不能对不存在的结果调用函数?
-
“我不能返回任何东西,因为我使用递归”没有任何意义。尤其是在递归的情况下,你总是需要
return一些东西。即使它只是递归调用的结果。 -
@Cruiser 我不知道如何将异步方法与不返回任何内容的函数一起使用。
-
你在尝试使用承诺吗?您的
parseRequestAndCreateCarList和carListParsing函数中没有任何异步内容!
标签: javascript promise