使用async/await定义报错:Promise executor functions should not be async.eslintno-async-promise-executor?

现有这样的定义async/await的场景:


const getOSQueryBuilder = async (): Promise<Repository<ConfigEntities>> => {
  return Database.getRepository(ConfigEntities)
}

class OSService {
  // 根据ID查询操作
  static async getConfig(id: string): Promise<unknown> {
    return new Promise(async (resolve) => {  // 这里的async会弹窗报错
      const osQueryBuilder = await getOSQueryBuilder()
      const data = (await osQueryBuilder).findOne({
        where: {
          id
        }
      })
      resolve(data)
    })
  }
}

报错信息:
QQ_1725354439816.png

Promise executor functions should not be async.eslintno-async-promise-executor

请问这里应该如何整改呢?

阅读 1.3k
2 个回答

你把异步抽成一个函数 调用就行了 这样 Promise executor 本身就不是异步函数了

const getOSQueryBuilder = async (): Promise<Repository<ConfigEntities>> => {
  return Database.getRepository(ConfigEntities)
}

class OSService {
  // 根据ID查询操作
  static async getConfig(id: string): Promise<unknown> {
    return new Promise((resolve) => {  // 这里的async会弹窗报错
      async function inquire() {
        const osQueryBuilder = await getOSQueryBuilder()
        const data = (await osQueryBuilder()).findOne({
          where: {
            id
          }
        })
        resolve(data)
      }
      inquire();
    })
  }
}

将 async 改为回调:

const sleep = (ms: number) => new Promise(r => setTimeout(r, ms))

new Promise(async r => {
    await sleep(1000)
    r(1)
})

new Promise(r => {
    sleep(1000).then(() => {
        r(1)
    })
})
推荐问题
logo
Microsoft
子站问答
访问
宣传栏