我正在使用异步等待函数,我需要在某个过程后调用相同的函数。
这个想法是,例如,我有一个具有父子关系的表,我需要按顺序显示所有父项和子项。但关卡深度未知
Fruit > Red > Cherry > europ cherry
Fruit > Red > Cherry > japan cherry
Fruit > yellow> banana > ... > ....
Fruit > green> light green> apple > ... > ...
Fruit > green> dark green> apple > ... > ...
我需要得到:
Fruit
_RED
__Cherry
___Europe Cherry
___Japan Cherry
_Yellow
__Banana
_Green
__Light green
___Apple
____...
_____...
感谢您的帮助。
const getChildren = async parent => {
const children = await Title_Title.findAll({
// include: [{ model: Title }],
where: { parentId: parent }
}).map(plain)
if (children.length) {
return children.forEach(child => {
return getChildren (child.childId)
})
}
}
它给了我错误 promise
最佳答案
Array.prototype.forEach()
不返回任何内容。您可能正在那里寻找Array.prototype.map()
。另外,当您将函数指定为异步时,您是说它返回一个 Promise。无论您在何处调用 getChildren
,都需要 await
或使用 .then()
,可能包括函数本身内部的嵌套调用。尽管出于性能原因,您实际上可能希望在嵌套调用中执行类似于 await Promise.all(children.map(child => getChildren(child.childId)))
的操作。
编辑:也可能存在问题,因为如果没有子项,您的函数将返回未定义。我建议删除 if (children.length)
并在没有子项时让它解析为空数组。
关于javascript - 在同一函数内调用函数(异步),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57125086/