gpt4 book ai didi

javascript - NodeJS 的递归 Promise 不会终止

转载 作者:行者123 更新时间:2023-11-30 23:54:54 25 4
gpt4 key购买 nike

我编写了以下函数来重建包含递归的 JSON 对象。但是在执行时,它不会返回任何内容,并且 console.log 一次又一次地记录相同的组件而不会终止。谁能帮我找出问题所在吗?

this.findOne = (id) => {
return new Promise(resolve => {
componentCollection.find(id).then(components => {
if (components[0]) {
let subComponents = components[0].components;
for (let i = 0; i < subComponents.length; i++) {
console.log(subComponents[i])
subComponents[i] = resolve(this.findOne(subComponents[i].id))
}
components[0].components = subComponents;
}
resolve(components[0])
})
})
}

编辑:组件包含仅包含 id 作为属性。这就是为什么我必须像这样递归地构建它。我尝试了另一种方法,最终得到了相同的无限日志:

this.findOne = async (id) => {
let components = await componentCollection.find(id)
if (components[0]) {
let subComponents = components[0].components;
for (let i = 0; i < subComponents.length; i++) {
console.log(subComponents[i])
subComponents[i] = await this.findOne(subComponents[i].id)
}
components[0].components = subComponents;
}
return components[0]
}

两者都一次又一次地尝试记录父组件的第一个子组件。

我尝试构建的对象:

{
id:1,
name:"comp1",
components:[
{
id:2,
name:"comp2",
components:[
{
id:3,
name:"comp3"
},
{
id:4,
name:"comp4"
}
]
}
]
}

来自 console.log(subComponents[i]) 的控制台无限日志:

{
id:2,
name:"comp2",components:[..]
}

编辑:

findOne周边代码:

this.findone = () =>{}
module.exports = {
findOne: this.findOne
};

我在 Controller 中将其称为:

const ComponentService = require('./cs');
const component = await ComponentService.findOne(id)//id={1,2,...}

最佳答案

这是一个使用 Promise 的版本。想必将其转换为async-await 很容易。它使用纯函数,而不是对象的方法。改变这一点应该不难;我没有尝试过,但您可能必须存储对 this 的本地引用才能使其工作。

const findOne = (id) => new Promise (
(resolve, reject) =>
componentCollection .find (id) .then (
({components = [], ...rest}) =>
Promise .all (components .map (({id}) => findOne (id))) .then (
children => resolve ({...rest, components: children}),
reject
),
reject
)
)

findOne (5) .then (console .log, console .warn)

findOne (1) .then (console .log, console .warn)
.as-console-wrapper {min-height: 100% !important; top: 0}
<script>
// Dummy code just for demonstration
const componentCollection = {
find: (n) => [1, 2, 3, 4] .includes (n)
? Promise .resolve (
n == 1
? {id: 1, name: 'comp1', components: [{id: 2}]}
: n == 2
? {id: 2, name: 'comp2', components: [{id: 3}, {id: 4}]}
: n == 3
? {id: 3, name: 'comp3'}
: {id: 4, name: 'comp4'}
)
: Promise .reject (`Not found: ${n}`)
}
</script>

这里的要点是使用 Promise.all将子组件的 Promise 列表转换为单个 Promise,然后您可以附加到该 Promise。

关于javascript - NodeJS 的递归 Promise 不会终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61123864/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com