Skip to content Skip to sidebar Skip to footer

How Can I Reorganize My Return In An Async Function?

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

Solution 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:

asyncfindById(id) {
    try {
        let user = awaitthis.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.

Post a Comment for "How Can I Reorganize My Return In An Async Function?"