Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/opencv/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 异步、等待和承诺捕获错误_Javascript_Promise_Async Await_Ecmascript 2017 - Fatal编程技术网

Javascript 异步、等待和承诺捕获错误

Javascript 异步、等待和承诺捕获错误,javascript,promise,async-await,ecmascript-2017,Javascript,Promise,Async Await,Ecmascript 2017,我有一个关于在async和wait中捕获用户错误的问题 比方说,我有一个只为单个用户获取的路由 routes.js routes.get('/getuserbyid/:id', (req, res) => { const id = req.params.id; accountController.getById(id) .then((result) => { res.json({ confir

我有一个关于在async和wait中捕获用户错误的问题

比方说,我有一个只为单个用户获取的路由

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;
        }
}
因此,无论发生什么情况,我都会得到一条空记录或一条记录。这仍然是一个成功。 在Promissions中,我可以拒绝null,因此它将显示在路由的catch块中。现在,使用async和Wait。如何在错误块中设置空值以实现相同的效果

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

}

如果值为空,则可以直接抛出和异常

export const getById = async (id) => {
        const user = await users.findOne({ where: {
                id: id
            }});

        if (!user) {
            throw Error('User does not exist..');
        }
        return user;        
}

async
函数总是返回一个
Promise

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

考虑

函数getValue(){
返回承诺。拒绝(空);
}
getValue().catch(e=>{
log('getValue'引发的An被a使用'.catch`方法捕获);
控制台日志(e);
});
(异步函数main(){
试一试{
等待getValue();
}捕获(e){
log('getValue'引发的事件被catch块捕获);
控制台日志(e);
}

}());首先,避免承诺反模式。您有一个返回承诺的函数,无需将其包装在
newpromise()

那么您的函数可以如下所示:

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

      return user;
    });
}
这个的异步/等待版本是

export const getById = async (id) => {
  const user = await users.findOne({ where: { id } });

  if(user === null)
    throw 'User does not exist';

  return user;
}

您将
抛出null我可以在这里看到一些问题。首先,严格测试
(user==null)
可能缺少一些错误案例,例如
未定义的
。第二,尝试/捕获是不必要的,并且可能会消失。如果
user
不是有效的用户对象,只需立即抛出一个错误即可。它将由您的<代码> .CcCh()/Case>回调处理。这将不起作用,因为您处于一个尝试/ catch的中间,将抛出错误,然后从异步函数返回,这不是允诺应该如何工作。只需完全卸下try/catch包装,效果会更好。谢谢!这正是我需要的。