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,我们可以做这样的事情。
谢谢。
答案 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)
}