【问题标题】:Typescript with Mongoose EXEC() function async/await带有 Mongoose EXEC() 函数 async/await 的打字稿
【发布时间】:2017-08-26 10:34:38
【问题描述】:

我正在尝试将 Typescript 与 Express 和 Mongoose 一起使用。到目前为止,结果是惊人的。然而,我被困在一个很小的部分。

前提:我正在使用 EXEC() 执行 Mongoose 查询

let result = await UserModel.User.find().exec();

我必须使用 async / await 因为在此行之后有一些处理,我想避免整个回调

问题

我需要从查询返回的结果对象中获取 {err, data}。但是目前它只是保存整个数据,我无法执行错误处理

所以当我使用 async/await

时需要一种方法来获取 mongoose 错误描述

【问题讨论】:

  • 你是否承诺过这个方法:UserModel.User.find().exec(); .这不返回回调吗??
  • 我通过使用 async 和 await 来避免回调

标签: node.js mongodb typescript mongoose


【解决方案1】:

使用async/await 的错误处理是通过使用try/catch 完成的:

try {
  let result = await UserModel.User.find().exec();
  ...
} catch(err) {
  ...
}

【讨论】:

    【解决方案2】:

    尝试使用库 await-to-js

    例子:

    const to = require('await-to-js').default

    const [err, result] = await to(func()) if (err) 抛出错误

    ...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-09
      • 1970-01-01
      • 2019-04-15
      • 2021-08-06
      • 2017-12-12
      • 1970-01-01
      相关资源
      最近更新 更多