How can I reorganize my return in an async function?

怎甘沉沦 提交于 2020-01-06 04:36:48

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!