我如何编辑我的此功能以获取所有用户?我刚刚开始学习异步等待,并且我很难学习如何获取请求正文。 这是我的功能:
export const get: Operation = async (
req: express.Request,
res: express.Response
) => {
commonUtility.showRequestParam(req);
let users: db.IUserDocument[] = [];
try {
// Describe data acquisition and registration from mongoDB here.
users = await UserModel.find()
.then(data => {
return data;
})
.catch(err => {
throw err;
});
} catch (err) {
// Error.
api.responseError(res, err);
}
if (users.length < 1) {
// this case is 404 ???
api.responseJSON(res, 200, []);
}
};
这是我的用户模型:
export const usersSchema = new Schema({
username: {
type: String,
required: true
},
email: {
type: String,
required: true
},
password: {
type: String,
required: true
},
BaseFields
});
export const UserModel = mongoose.model<db.IUserDocument>('Users', usersSchema);
答案 0 :(得分:1)
使用.then
和async
时不需要使用await
export const get: Operation = async (
req: express.Request,
res: express.Response
) => {
commonUtility.showRequestParam(req);
let users: db.IUserDocument[] = [];
try {
users = await UserModel.find();
api.responseJSON(res, 200,users);
} catch (err) {
// Error.
api.responseError(res, err);
}
};
在此处详细了解异步等待-> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function