我正在使用loopback 3
来构建REST服务,我想使用async / await而不是必须使用回调。所以不要这样做:
MyModel.myFunction = (callback) => {
MyModel.find({where: {id: 2}}, (e, data) => {
if (e) return callback(e);
callback(null, data);
});
};
我更愿意这样做:
MyModel.myFunction = async (callback) => {
try {
const data = await MyModel.find({where: {id: 2}});
callback(null, data);
} catch (e) {
console.error(e);
callback(e);
}
};
回调方法完美无缺 - async / await会产生很多错误:
UnhandledPromiseRejectionWarning: Error: Callback was already called.
UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch().
怎么了?我无法解决这个问题。
答案 0 :(得分:8)
一些重构:
MyModel.myFunction = async () => {
try {
const data = await MyModel.find({where: {id: 2}});
return data; // it's enough as the async means it returns a promise
} catch (e) {
console.error(e);
throw e;
}
};
如果您不需要记录错误(环回错误处理程序将其记录而不是您),则会出现此情况:
MyModel.myFunction = async () => {
return MyModel.find({where: {id: 2}});
};
答案 1 :(得分:0)
看起来我只是混合了两个概念,这就是解决方案:
MyModel.myFunction = async (callback) => {
try {
const data = await MyModel.find({where: {id: 2}});
return Promise.resolve(data);
} catch (e) {
console.error(e);
return Promise.reject(e);
}
};
答案 2 :(得分:0)
一种更简单的方法是只使用一个函数来解决您的诺言,然后将db查询传递给它,就像这样。
async function ReturnWithResolvedPromise(dbQuery) {
try {
return Promise.resolve(dbQuery);
} catch (e) {
return Promise.reject(e);
}}
然后这样称呼
let result = await ReturnWithResolvedPromise(await Users.count({where: {Region: 'UK'}}));