问题
let's say I've got a function where I'm fetching for some data from a DB.
findById(id) {
return Model.findById(id)
}
I need to reorganize the return from the user data like this:
{
name: "Tom",
age: 57
}
into something like this:
{
message: "User is found successfully",
success: true,
user: user
}
So far I can manage with that with a Promise "then" section, like this:
return Model.findById(id)
.then(user => {
if (!user) {
logger.warn(`Coundn't find user with id: ${id}`);
return { message: `Coundn't find user with id: ${id}`, success: false, user: null };
}
return { message: `User with id: ${id}`, success: true, user: user };
})
.catch(err => {
if (err) {
logger.error(err.message);
return { message: err.message, success: false, user: null };
}
})
Can I do the same with a async/await and return my reorninazed return?
Because so far it returns the user object from the DB:
async findById(id) {
return await this.model.findById(id, function (user, err) {
if (err) {
console.log('test');
logger.error(err);
return { message: err.message, success: false, user: null };
}
if (!user) {
logger.warn(`Coundn't find user with id: ${id}`);
return { message: `Coundn't find user with id: ${id}`, success: false, user: null };
}
return { message: `User with id: ${id}`, success: true, user: user };
});
}
Thanks in advance!
回答1:
Most database APIs do NOT support both a callback and a promise at the same time. If you pass a callback, they do not return a promise. Pick one style or the other. Your first approach using .then() works just fine as that is all promise-based.
Your second approach does not work because you're passing a regular callback. That tells the database to NOT return a promise because you're using the older callback style, but you're trying to use that promise.
If you want to use async/await, you could do so like this:
async findById(id) {
try {
let user = await this.model.findById(id);
if (user) {
return { message: `User with id: ${id}`, success: true, user: user };
} else {
logger.warn(`Coundn't find user with id: ${id}`);
return { message: `Coundn't find user with id: ${id}`, success: false, user: null };
}
} catch(e) {
logger.error(err);
return { message: err.message, success: false, user: null };
}
}
FYI, you can remove the if (err) test in the .catch() handler from your first code block. If .catch() is triggered, there is an error - you don't need to test if one is there.
来源:https://stackoverflow.com/questions/59507000/how-can-i-reorganize-my-return-in-an-async-function