NodeJS:承诺上的 Eslint 错误

Posted

技术标签:

【中文标题】NodeJS:承诺上的 Eslint 错误【英文标题】:NodeJS: Eslint errors on promises 【发布时间】:2021-01-08 12:58:00 【问题描述】:

我有两个来自 eslint 的错误:

错误 Promise 在函数参数中返回,其中返回的是 void 预期错误 Promise 执行器函数不应该是异步的

它们来自以下代码:

      const promiseFeature = new Promise(async (resolve) => 
      let objectProfile = await this.userFeaturesRepository.findById(id);
      objectProfile = await this.userFeaturesRepository.getProfileObj(myUserFeatures);
      await this.userFeaturesRepository.updateById(id, objectProfile);
      resolve()
    )
    
      const promiseIAM = new Promise(async (resolve) => 
      let objectIAM = await this.userIAMRepository.findById(id);
      objectIAM = await this.userIAMRepository.getIAMObj(myUserFeatures);
      objectIAM.email = objectIAM.email.toLowerCase();
      await this.userIAMRepository.updateById(id, objectIAM);
      resolve()
      )

      await Promise.all([promiseFeature, promiseIAM]);

代码有效,但我真的不知道谁来解决 eslint 问题。

谢谢, 提前。

【问题讨论】:

这能回答你的问题吗? Is it an anti-pattern to use async/await inside of a new Promise() constructor? 【参考方案1】:

试试这个:

const promiseFeature = new Promise((resolve) => 
    (async() => 
        let objectProfile = await this.userFeaturesRepository.findById(id);
        objectProfile = await this.userFeaturesRepository.getProfileObj(myUserFeatures);
        await this.userFeaturesRepository.updateById(id, objectProfile);
        resolve()
    )();
)
    
const promiseIAM = new Promise((resolve) => 
    (async() => 
        let objectIAM = await this.userIAMRepository.findById(id);
        objectIAM = await this.userIAMRepository.getIAMObj(myUserFeatures);
        objectIAM.email = objectIAM.email.toLowerCase();
        await this.userIAMRepository.updateById(id, objectIAM);
        resolve()
    )();
)

await Promise.all([promiseFeature, promiseIAM]);

我猜这里发生的事情是 ESLint 期望你的 Promise 中的回调函数返回 void,但他们正在返回 Promise,因为它们是 async

请参阅this page from MDN 上的“返回值”部分。

【讨论】:

以上是关于NodeJS:承诺上的 Eslint 错误的主要内容,如果未能解决你的问题,请参考以下文章

ESlint:Promise和Async的配置

由于 `(node:77921) fs: ...` 错误,无法`npm install eslint`

nvmnodenpm安装以及pycharm配置eslint

Nodejs - 将属性上的承诺数组解析为对象数组

NodeJs分页,递归承诺问题

ESLint 可以帮助你防止 Unhandled-Promise-Rejections 吗?