哪个猫鼬查询使用异步等待失败

时间:2021-06-30 13:41:03

标签: node.js mongodb express mongoose async-await


我有一个小要求。
我正在尝试将文档添加到 2 个不同的集合中,如下所示。在下面的代码中,**Test1_Model** 和 **Test2_Model** 是 Node.js 中的 Mongoose 模型。
try {
  const test1 = new Test1_Model({ name: "Dummy" });
  const saveTest1 = await test1.save();
  const test2 = new Test2_Model({ field: "Something" })
  const saveTest2 = await test2.save();
} catch(err) {
  console.log(err);
}

现在的要求是知道上面哪个猫鼬查询返回了错误,哪个成功完成了。是的,如果 test1.save() 失败,那么 test2.save() 不会只执行,但可能存在 test1.save() 完成但 test2.save 的情况() 失败。所以我们的目的是要知道到底哪个查询失败了。

上述问题可以通过使用 .then().catch() 将 async/await 替换为 Promise 处理来解决。您可以在下面找到该解决方案。

try {
  const test1 = new Test1_Model({ name: "Dummy" });
  const saveTest1 = test1.save().then().catch(err => {
    throw new Error('Test1 Failed');
  });
  const test2 = new Test2_Model({ field: "Something" })
  const saveTest2 = test2.save().then().catch(err => {
    throw new Error('Test2 Failed');
  });
} catch(err) {
  console.log(err);
}

这解决了问题,但目的是知道通过使用 async/await,我们可以做这样的事情。

谢谢。

1 个答案:

答案 0 :(得分:1)

您可以为每个承诺创建一个包装器并抛出错误或从中传递数据。

const promiseHandler = (promise) => {
  return promise
    .then(data => ([data, undefined]))
    .catch(error => Promise.resolve([undefined, error]));
}
try {
  const test1 = new Test1_Model({ name: "Dummy" });
  const [saveTest1, error] = await handle(test1.save());
  if (error) throw new Error(`Error is on saveTest ${error}`)
  const test2 = new Test2_Model({ field: "Something" })
  const [saveTest2, error] = await handle(test2.save());
  if (error) throw new Error(`Error is on saveTest2 ${error}`)
} catch (error) {
        console.log(error)
}