首页 文章

异步并等待并承诺捕获错误

提问于
浏览
2

我有一个关于在异步和等待中捕获用户错误的问题 .

假设我有一条仅为单个用户提取的路由 .

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
            });
        });
});

我有一个控制器来获取请求 . 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;
        }
}

所以无论发生什么,我都会获得空或单个记录 . 它仍然是成功的 . 在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);
            });
    });

}

3 回答

  • 1

    首先,避免使用Promise反模式 . 你有一个返回Promise的函数,不需要在_140726中包装它 .

    然后你的功能可能如下所示:

    export const getById = (id) => {
      return users.findOne({ where: { id } })
        .then((user) => {
          if (user === null)
            throw 'User does not exit';
    
          return user;
        });
    }
    

    和async / await版本是

    export const getById = async (id) => {
      const user = await users.findOne({ where: { id } });
    
      if(user === null)
        throw 'User does not exist';
    
      return user;
    }
    
  • 0

    async 函数始终返回 Promise .

    async 函数中使用 throw 构造会拒绝返回的 Promise .

    考虑

    function getValue() {
      return Promise.reject(null);
    }
    
    getValue().catch(e => {
      console.log('An raised by `getValue` was caught by a using the `.catch` method');
      console.log(e);
    });
    
    
    (async function main() {
      try {
        await getValue();
      } catch (e) {
        console.log('An raised by `getValue` was caught by a catch block');
        console.log(e);
      }
    }());
    
    async function getValue() {
      throw null;
    }
    
    getValue().catch(e => {
      console.log('An raised by `getValue` was caught by a using the `.catch` method');
      console.log(e);
    }); 
    
    (async function main() {
      try {
        await getValue();
      } catch (e) {
        console.log('An raised by `getValue` was caught by a catch block');
        console.log(e);
      }
    }());
    

    异步方法中的 try 块处理同步和异步错误 .

    考虑

    function throws() {
      throw Error('synchronous failure');
    }
    
    
    async function rejects() {
      throw Error('asynchronous failure');
    }
    
    (async function main() {
      try {
        throws();
      } catch (e) {
        console.log('asynchronously handled', e.message);
    
      }
    
      try {
        await rejects();
      } catch (e) {
        console.log('asynchronously handled', e.message);
      }
    }());
    

    要记住的一个关键点是,如果您忘记了拒绝使用它们的承诺,则不会捕获异步错误 . 这是忘记 .then 内部的 return.catch 回调的类比

  • 6

    如果你的值变空,你可以抛出异常 .

    export const getById = async (id) => {
            const user = await users.findOne({ where: {
                    id: id
                }});
    
            if (!user) {
                throw Error('User does not exist..');
            }
            return user;        
    }
    

相关问题