promise.resolve() 在 for 循环中 return 未定义

promise.resolve() in for loop return undefined

我试图在搜索过程后得到一个树节点。但它总是 return undefined.. 这是代码。

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)
        });
      }
      // ...

这应该有效。但是,此实现对 'resolve' 有太多无用的调用。最好直接找到匹配的项目并解决。

这是一个例子:

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
    }
  })
}