调用异步函数而不用等待阻塞线程

时间:2019-09-16 07:33:12

标签: javascript node.js asynchronous async-await

在快速路由中,我要记录用户对数据库的访问,而无需:

  • 等待它完成,然后再执行用户想要的任务
  • 关心日志记录是否成功

我想知道代码是否正确执行此操作。

此线程(Down-side on calling async function without await)本质上发布了相同的问题,但响应是避免使函数异步。但是,由于sequelize的{​​{1}}返回了一个Promise,所以我不确定在下面的代码中是否正确执行了此操作。谁能验证?

我还注意到,如果您不等待异步函数的try-catch块中的诺言,则在诺言中引发的任何错误都将无法处理。因此,我确保upsert能够捕获并处理所有错误。这是做事的正确方法吗?

logAccess

1 个答案:

答案 0 :(得分:1)

不等待就抓不到:

const foo = () => Promise.reject('foo');

const bar = async() => {
  try {
    foo();
  } catch (e) {
    console.log('error caught');
  }
}

bar();

我至少得到了“未捕获(承诺)”。

我会遇到诺言风格的错误

    logAccess(user).catch(someErrorHandlingFunction);

或在我不等待的单独功能中:

const logAccessAndCatchErrors = async (user) => {
    try {
        await logAccess(user);
    } catch(e) {
// put something here
    }
}

//...
logAccessAndCatchErrors(user);  // not `await logAccessAndCatchErrors(user)`