async并等待并承诺捕获错误

时间:2018-02-08 20:28:52

标签: javascript promise async-await ecmascript-2017

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

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

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 个答案:

答案 0 :(得分:6)

首先,避免使用Promise反模式。你有一个返回Promise的函数,不需要在new Promise()中包含它。

然后你的功能看起来像这样:

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

答案 1 :(得分:1)

async函数始终返回Promise

throw函数中使用async构造会拒绝返回的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);
  }
}());




要记住的一个关键点是,如果忘记await拒绝它们的承诺,将不会捕获异步错误。这类似于忘记return内部.then.catch回调

答案 2 :(得分:0)

如果您的值变空,您可以抛出异常。

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

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