Mongoose promise 和 sonarqube
Mongoose promise and sonarqube
我喜欢 async await 语法,我在 mongoose 中经常使用它。
所以在我的项目中有很多:
const user = await User.findOne({
_id: req.params.id
})
正如预期的那样工作。但是,在 sonarqube 中,我有这些错误:
Refactor this redundant 'await' on a non-promise.
声纳曲规则 i :
It is possible to use await on values which are not Promises, but it's
useless and misleading. The point of await is to pause execution until
the Promise's asynchronous code has run to completion. With anything
other than a Promise, there's nothing to wait for.
This rule raises an issue when an awaited value is guaranteed not to be a Promise.
Noncompliant Code Example
let x = 42;
await x; // Noncompliant
Compliant Solution
let x = new Promise(resolve => resolve(42));
await x;
let y = p ? 42 : new Promise(resolve => resolve(42));
await y;
我正在使用 mongo 4.0 和 mongoose 5.3.1
因为我可以使用 .then
、.catch
语法,所以我认为我正在处理 promise 那么我该如何解决呢?
如评论中所述,这是误报,更准确地说是贬低警告。
您可以忽略它,也可以在导入语句之后立即将其添加到您的代码中:
mongoose.Promise = Promise;
我对SonarQube
了解不多。我刚刚发现 SonarQube
是检查代码质量的工具,它需要 await
仅以 promises
为前缀,并且 mongoose
即使有 .then
也会失败.
Mongoose 查询不 return "fully-fledged" 承诺,即使他们有 .then()
。因此,为了获得 "fully-fledged" 承诺,您需要使用 .exec()
函数。
const user = await User.findOne({ _id: req.params.id }).exec()
我喜欢 async await 语法,我在 mongoose 中经常使用它。
所以在我的项目中有很多:
const user = await User.findOne({
_id: req.params.id
})
正如预期的那样工作。但是,在 sonarqube 中,我有这些错误:
Refactor this redundant 'await' on a non-promise.
声纳曲规则 i :
It is possible to use await on values which are not Promises, but it's useless and misleading. The point of await is to pause execution until the Promise's asynchronous code has run to completion. With anything other than a Promise, there's nothing to wait for.
This rule raises an issue when an awaited value is guaranteed not to be a Promise.
Noncompliant Code Example
let x = 42;
await x; // Noncompliant
Compliant Solution
let x = new Promise(resolve => resolve(42));
await x;
let y = p ? 42 : new Promise(resolve => resolve(42));
await y;
我正在使用 mongo 4.0 和 mongoose 5.3.1
因为我可以使用 .then
、.catch
语法,所以我认为我正在处理 promise 那么我该如何解决呢?
如评论中所述,这是误报,更准确地说是贬低警告。
您可以忽略它,也可以在导入语句之后立即将其添加到您的代码中:
mongoose.Promise = Promise;
我对SonarQube
了解不多。我刚刚发现 SonarQube
是检查代码质量的工具,它需要 await
仅以 promises
为前缀,并且 mongoose
即使有 .then
也会失败.
Mongoose 查询不 return "fully-fledged" 承诺,即使他们有 .then()
。因此,为了获得 "fully-fledged" 承诺,您需要使用 .exec()
函数。
const user = await User.findOne({ _id: req.params.id }).exec()