gpt4 book ai didi

javascript - for循环中的promise.resolve()返回未定义

转载 作者:行者123 更新时间:2023-12-02 20:56:19 28 4
gpt4 key购买 nike

我试图在搜索过程后获取一个树节点。但它总是返回未定义..这是代码。

const findOrder = (list, key) =>
new Promise((resolve) => {
for (let i = 0; i < list.length; i++) {
// find node through key in tree
if (list[i].key === key) {
console.log(`================I got it!: `, list[i].children); // children[]
resolve(list[i].children);
}
if (list[i].children) {
findOrder(list[i].children, key);
}
}
});

const setOrder = async() => {
const orders = await findOrder(
treeData,
dropObj.classKind === "1" ? keyGen(dropObj.key) : dropObj.key
);
console.log(`==================siblings: `, orders); // undefined
};
setOrder();

有什么问题吗?

最佳答案

你没有在这里解决它,

      // ...
if (list[i].children) {
findOrder(list[i].children, key);
}
// ...

为了让外部 Promise 知道何时解决它,您应该明确地这样做:

      // ...
if (list[i].children) {
findOrder(list[i].children, key).then(result => {
// as resolve can only be called once,
// do not call it if it doesn't found anything
if (result) resolve(result)
});
}
// ...

这应该有效。然而,这个实现有太多无用的调用来“解决”。最好直接找到匹配项并解决。

这是一个例子:

const findOrder = function (list, key) {
return new Promise((resolve, reject) => {
resolve(find(list, key))

function find (_list, key) {
for (let i = 0; i < _list.length; i++) {
if (_list[i].key === key) return _list[i].children
if (_list[i].children) {
const c = find(_list[i].children, key)
if (c) return c
}
}
return undefined
}
})
}

关于javascript - for循环中的promise.resolve()返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61475440/

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