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



我有一个小需求
我正在尝试将文档添加到两个不同的集合中,如下所示。在下面的代码中,**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(。因此,目的是确切地知道哪个查询失败了

通过使用.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,我们可以做这样的事情。

谢谢。

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

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

最新更新