Javascript 如何在承诺内正确实现mongodb async/Wait?
我读过,在Javascript 如何在承诺内正确实现mongodb async/Wait?,javascript,mongodb,promise,async-await,Javascript,Mongodb,Promise,Async Await,我读过,在承诺中包含一个async是async/await的反模式。下面的代码可以工作,但我很好奇,如果没有Promise中的async,如何实现同样的结果 如果我删除它,linter会告诉我如何不能在mongodb查询中使用wait。如果我在mongodb查询中删除wait,那么它就不会等待结果 export const getEmployees = (companyId) => { return new Promise(async (resolve, reject) => {
承诺中包含一个async是async/await的反模式。下面的代码可以工作,但我很好奇,如果没有Promise
中的async
,如何实现同样的结果
如果我删除它,linter会告诉我如何不能在mongodb查询中使用wait。如果我在mongodb查询中删除wait,那么它就不会等待结果
export const getEmployees = (companyId) => {
return new Promise(async (resolve, reject) => {
const employees = await Employees.find(
{ companyId },
);
// other logic here...
resolve({
employees,
});
});
谢谢。async
函数会自动返回Promise
s,它最终会用返回的任何表达式进行解析。只需将getEmployees
设为async
函数:
export const getEmployees = async (companyId) => {
const employees = await Employees.find(
{ companyId },
);
// other logic here...
return { employees };
};
(但要确保getEmployees
的消费者中捕获,以防出现错误)正如回答的那样,这是使用async/await从mongoDB检索数据的完美方式,我想补充一些关于如何处理这种情况下的错误的更多信息,以确保系统的正确性,以及更好的错误处理,以便向客户端返回关于其请求的更好状态
我想说的是,您通常希望捕获异步/等待调用中的所有异常
try {
const employees = await Employees.find({
companyId
});
// You can add more logic here before return the data.
return {
employees
};
} catch (error) {
console.error(error);
}
现在让我们检查一下处理可能发生的错误的方法
在错误范围内处理错误
为catch块中的变量指定默认值
检查错误实例并相应地采取行动
在我看来,这是在这些情况下处理错误最常见的方法,也是最优雅的方法。
在错误范围内处理错误:
export const getEmployees = async (companyId) => {
try {
const employees = await Employees.find({
companyId
});
// You can add more logic here before return the data.
return {
employees
};
} catch (error) {
console.error(error);
}
};
为catch块中的变量指定默认值:
export const getEmployees = async (companyId) => {
let employees;
try {
employees = await Employees.find({
companyId
});
// You can add more logic here before return the data.
employees = employees;
} catch (error) {
console.error(error);
}
if (employees) { // We received the data successfully.
console.log(employees)
// Business logic goes here.
}
return employees;
};
检查错误实例并采取相应措施:
export const getEmployees = async (companyId) => {
try {
const employees = await Employees.find({
companyId
});
// You can add more logic here before return the data.
return {
employees
};
} catch (error) {
if (error instanceof ConnectionError) {
console.error(error);
} else {
throw error;
}
}
};
还有一些关于异步的解释,以及在这些答案中可以找到的更有用的方法。
Mm,消费者也是一个异步函数吗?因为消费者需要知道是否抛出了错误,所以您可以让员工;try{employees=await getEmployees(companyId);}catch(e){/*handle*/}
@Woppi-承诺的规则之一(因此,async
/await
,因为async
/await
只是承诺创建和消费的语法糖)是:必须处理错误,或者将承诺传播给处理错误的东西(等等;某个地方必须处理错误的东西)。因此,如果您在另一个async
函数中使用getEmployees
,那么另一个函数的调用方必须要么处理(通过try
/catch
)要么传播(通过返回从getEmployees
承诺派生的承诺)。@Woppi-您不需要包。只是处理错误。特别是对于async
/await
,它非常简单。@AnthonyWinzlet-async
/await
由刚刚发布的最新JavaScript规范(ES2018)定义,并且在最新版本的Chrome、Firefox、Edge和Node.js中得到支持。更多:@T.J.Crowder收到了。。。非常感谢您的澄清