Pak*_*Chu 2 javascript promise async-await ecmascript-2017
我有一个关于在异步和等待中捕获用户错误的问题.
假设我有一条仅为单个用户提取的路由.
routes.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
});
});
});
Run Code Online (Sandbox Code Playgroud)
我有一个提取请求的控制器.accountController.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;
}
}
Run Code Online (Sandbox Code Playgroud)
所以无论发生什么,我都会得到一个空或一个记录.它仍然是成功的.在promises中,我可以拒绝null,因此它将显示在路径中的catch块中.现在用异步和等待.如何在错误块中实现相同的null?
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);
});
});
}
Run Code Online (Sandbox Code Playgroud)
首先,避免使用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;
});
}
Run Code Online (Sandbox Code Playgroud)
和async/await版本是
export const getById = async (id) => {
const user = await users.findOne({ where: { id } });
if(user === null)
throw 'User does not exist';
return user;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2888 次 |
| 最近记录: |