创建新的 Promise 而不是使用 then() JS

creating new Promise instead of using then() JS

我将 nexus 用于我的数据库目的,但我有一个问题通常也适用于 JS/TS。

knex('cars').insert(cars).then(() => console.log("data inserted"))
    .catch((err) => { console.log(err); throw err })
    .finally(() => {
        knex.destroy();
    });

我如何将上面的内容创建为新的 Promise 并 reject 或 resolve 看起来像这样

byID(id: string): Promise<TEntity> {
    return new Promise((resolve, reject) => {
      const result = pg(cars)
      .where({ 'id': id })
      //   .andWhere('age', '<', 18);
        .first();
        if (!result)
            return reject(new ModelNotFoundError('LMAO user not found')); 
        resolve(result)
    })
  }

不确定这是否是您要的,但您可以利用 async/await。

const result = await new Promise(async (resolve, reject) => {
  try {
    await knex('cars').insert(cars);
    console.log("data inserted");
  } catch (err) {
    console.log(err);
    reject(err);
  } finally {
    knex.destroy();
  }
  resolve();
})

你不需要'await'这个承诺,你也可以在那个时候.then它。我要说明的要点是,您可以使 Promise 中的函数异步。

无需将 knex 查询包装到 promise 构造函数。您可能正在尝试编写如下内容:

byID(id: string): Promise<TEntity> {
    return pg(cars).where({ 'id': id }).first()
        .then(result => {
          if (!result) {
            throw new ModelNotFoundError('LMAO user not found')); 
          }
          return result;
        });
     })
  }