如何嵌套承诺(Promise.all内的Promise.all)

时间:2020-01-20 20:19:45

标签: javascript promise es6-promise

请考虑嵌套Promises的以下结构:

const getData = async() => {

  const refs = [{
      name: "John33",
      age: 33
    },
    {
      name: "John34",
      age: 34
    },
    {
      name: "John35",
      age: 35
    },
    {
      name: "John36",
      age: 36
    }
  ];


  let source = [{
      name: "John30",
      age: "unknown"
    },
    {
      name: "John31",
      age: "unknown"
    },
    {
      name: "John32",
      age: "unknown"
    },
    {
      name: "John33",
      age: "unknown"
    },
    {
      name: "John34",
      age: "unknown"
    },
    {
      name: "John35",
      age: "unknown"
    }, {
      name: "John36",
      age: "unknown"
    },
    {
      name: "John37",
      age: "unknown"
    },
    {
      name: "John38",
      age: "unknown"
    },
    {
      name: "John39",
      age: "unknown"
    }
  ];

  const resolver = doc => {
    return new Promise(doc => {
      let clone = { ...doc
      };
      let found = refs.find(ref => {
        return ref.name === doc.name;
      });

      if (found) clone.age = found.age;
      return clone;
    });
  };

  let getRefs = (doc, refs) => {
    const promises = refs.map(r => {
      resolver(doc).then(result => {
        return result;
      });
    });

    return Promise.all(promises);
  };


  let getCursorData = (cursor, refs, data) => {
    const promises = cursor.forEach(doc => {
      console.log("Getting cursor for " + doc.name);
      let clone = { ...doc
      };

      return getRefs(clone, refs).then(result => {
        console.log("Getting refs for " + clone.name);
        data.push(result);
      });
      return;
    });

    return Promise.all(promises);
  };

  // Get data
  let data = [];
  await getCursorData(source, refs, data);

  console.log("Returned data: ");
  console.log(data);

  return data;
};

console.log("Begin");
getData().then(result => {
  console.log("End");
  console.log(result)
});

由于某种原因,我没有到达代码的结尾({End未打印)。我怀疑存在一些头寸或缺少回报,但是我陷入困境而找不到解决方案。

如何使此代码结构按预期工作,如下所示:

  1. 遍历源代码(我的数据来自数据库
  2. 对于每个寄存器,应用参考更改(在示例中,更改 age
  3. 返回固定引用的数据

此代码的预期结果是使用当前的Promise结构获取固定了可用引用的原始数据(source):

[
      name: "John30",
      age: "unknown"
    },
    {
      name: "John31",
      age: "unknown"
    },
    {
      name: "John32",
      age: "unknown"
    },
    {
      name: "John33",
      age: 33
    },
    {
      name: "John34",
      age: 34
    },
    {
      name: "John35",
      age: 35
    }, {
      name: "John36",
      age: 36
    },
    {
      name: "John37",
      age: "unknown"
    },
    {
      name: "John38",
      age: "unknown"
    },
    {
      name: "John39",
      age: "unknown"
    }
]

1 个答案:

答案 0 :(得分:0)

你去哪里!

std::move()