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

时间:2020-04-28 08:03:31

标签: javascript reactjs es6-promise

我试图在搜索过程之后得到一个树节点。但是它总是返回未定义的。 这是代码。

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();

出什么问题了?

1 个答案:

答案 0 :(得分:1)

您在这里没有解决问题,

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