我有一个关于在异步和等待中捕获用户错误的问题。
假设我有一个只为单个用户获取的路由。
路由.js
routes.get('/getuserbyid/:id', (req, res) => {
const id = req.params.id;
accountController.getById(id)
.then((result) => {
res.json({
confirmation: 'success',
result: result
});
})
.catch((error) => {
res.json({
confirmation: 'failure',
error: error
});
});
});
我有一个 Controller 来获取请求。 账户 Controller .js
export const getById = async (id) => {
try {
const user = await users.findOne({ where: {
id: id
}});
if (user === null) {
return 'User does not exist';
}
return user;
} catch (error) {
return error;
}
}
所以无论发生什么,我都会得到一个空记录或一个记录。它仍然是成功的。 在 promise 中,我可以拒绝 null,因此它会出现在路由的 catch block 中。现在有了异步和等待。我怎样才能在错误 block 中实现相同的空值?
export const getById = (id) => {
return new Promise((resolve, reject) => {
users.findOne({ where: {
id: id
}})
.then((result) => {
if (result === null) {
reject('User does not exit');
}
resolve(result);
})
.catch((error) => {
reject(error);
});
});
}
最佳答案
首先,避免 Promise 反模式。您有一个返回 Promise 的函数,无需将其包装在 new Promise()
中。
然后你的函数看起来像这样:
export const getById = (id) => {
return users.findOne({ where: { id } })
.then((user) => {
if (user === null)
throw 'User does not exit';
return user;
});
}
这是异步/等待版本
export const getById = async (id) => {
const user = await users.findOne({ where: { id } });
if(user === null)
throw 'User does not exist';
return user;
}
关于javascript - 关于捕获错误的异步和等待和 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48694259/