javascript - 在同一函数内调用函数(异步)

标签 javascript asynchronous callback

我正在使用异步等待函数,我需要在某个过程后调用相同的函数。

这个想法是,例如,我有一个具有父子关系的表,我需要按顺序显示所有父项和子项。但关卡深度未知

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/

相关文章:

javascript - 如何在 Vue v-if 中使用异步函数?

iOS Swift : Closures (Callbacks) versus Delegates, 什么时候使用哪个?

javascript - 使用 mocha javascript 时如何模拟 dom 元素?

angular - 在 ngOnInit 异步调用函数吗?

javascript - 根据 Cookie 值显示/隐藏 div

c# - 如何使用 async/await 在 UI 线程上异步运行多个任务?

jquery - 带有缓动和回调函数的scrollTo

javascript - 尝试使用函数组合时出现 ReferenceError : error is not defined,

javascript - 强制定向布局从外部/内部数据链接获取特定数据

javascript - 一个 "fixed"<div>-Tag (Footer) resize height of another